还没有文档。但是在 WWDC2019 中,他们解释了它是什么以及如何使用它。链接在这里:
Apple WWDC 2019
假设您想在后台清理数据库以删除旧记录。首先,您必须在 Background Modes 功能中启用后台处理。然后在您的Info.plist 中添加后台任务调度程序标识符:
然后在 'ApplicationDidFinishLaunchingWithOptions' 方法中向任务注册您的标识符。
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.apple-samplecode.ColorFeed.db_cleaning", using: nil) { task in
// Downcast the parameter to a processing task as this identifier is used for a processing request
self.handleDatabaseCleaning(task: task as! BGProcessingTask)
}
在后台执行您想要执行的工作并将其放入操作队列中。在我们的例子中,清理函数如下所示:
// Delete feed entries older than one day...
func handleDatabaseCleaning(task: BGProcessingTask) {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
// Do work to setup the task
let context = PersistentContainer.shared.newBackgroundContext()
let predicate = NSPredicate(format: "timestamp < %@", NSDate(timeIntervalSinceNow: -24 * 60 * 60))
let cleanDatabaseOperation = DeleteFeedEntriesOperation(context: context, predicate: predicate)
task.expirationHandler = {
// After all operations are canceled, the completion block is called to complete the task
queue.cancelAllOperations()
}
cleanDatabaseOperation.completionBlock {
// Perform the task
}
// Add the task to the queue
queue.addOperation(cleanDatabaseOperation)
}
现在,当应用程序进入后台时,我们必须在BGTaskScheduler 中安排后台任务。
注意:BGTaskScheduler 是一项新功能,用于安排将在后台执行的多个后台任务]。
此后台任务将每周执行一次以清理我的数据库。查看您可以提及的属性以定义任务类型。