目前还没有文档可用。但在WWDC2019中,他们解释了它是什么以及如何使用它。以下是链接: Apple WWDC 2019
比如你想要在后台清理你的数据库以删除旧记录。首先,你需要在后台模式的功能中启用后台处理。然后在你的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
是一项新功能,可安排执行多个在后台执行的后台任务。
此后台任务将每周执行一次,以清理我的数据库。请查看您可以提到以定义任务类型的属性。
"后台处理"模式是运行BGTaskScheduler任务所必需的。
一种通过提交任务请求来调度在后台启动应用程序的任务的类。通过添加所需背景模式的功能以及添加任务标识符白名单来配置后台任务的应用程序。
配置后台任务的应用程序
Xcode背景模式
应用程序状态
foreground -> background -> suspended -> terminated
后台传输
- 在应用程序处于后台模式时执行某些任务。
为了添加在后台模式下工作的能力:
App Target -> Signing & Capabilities -> + Capability -> Background Modes