直接继承NSObject的类
classBGTaskScheduler:NSObject
用途:提交任务请求,在后台启动APP
Overview
为了省电。
步骤1配置
配置兼容性:在Signing & Capabilities.中勾选,fetch或processing
plist中添加任务id : 在target中的info标签的Custom iOS Target Properties分组中Permitted background task scheduler identifiers数组中添加任务ID 。 对应plist中的BGTaskSchedulerPermittedIdentifiers 。(这个配置禁用了2个回调application(_:performFetchWithCompletionHandler:) and setMinimumBackgroundFetchInterval(_:) )
步骤2 Registering, Scheduling, and Running Tasks
APP启动时,注册一个handler来执行任务。还注册和任务相关的id。在APP启动完成之前,就注册所有任务。什么算作启动完成?UIKITS自动处理该过程。期间可以回调你在APPDelegate中定义的函数。该过程的官网图
1.The app is launched, either explicitly by the user or implicitly by the system.
2.The Xcode-provided main function calls UIKit's UIApplicationMain(_:_:_:_:)function.
3.The UIApplicationMain(_:_:_:_:) function creates the UIApplication object and your app delegate.
4.UIKit loads your app's default interface from the main storyboard or nib file.
5.UIKit calls your app delegate's application(_:willFinishLaunchingWithOptions:) method.
6.UIKit performs state restoration, which calls additional methods of your app delegate and view controllers.
7.UIKit calls your app delegate's application(_:didFinishLaunchingWithOptions:)method .
该过程完成后。系统使用APPdelegate或Scenedelegate显示你的UI并管理周期。
注册代码:
BGTaskScheduler.shared.register ( forTaskWithIdentifier: "com.example.apple-samplecode.ColorFeed.refresh", using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
注册稍后,提交这个任务id的请求,或者以后需要更改配置时,也要提交以覆盖旧的。“稍后” 是什么时候呢?
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.example.apple-samplecode.ColorFeed.refresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do { try BGTaskScheduler.shared.submit(request) }
catch { print("Could not schedule app refresh: \(error)") }
}
当系统在后台执行你的任务:打开你的APP,并寻找你指定的handler。
你可以在handler里,第一句就再次scheduleAppRefresh( ) 。这样可以再提交一个新的请求(看来,这个任务调度机制类似timeout而不是interval )
通常先创建一个操作:
let operation = RefreshAppContentsOperation()
就算被执行了handler也可能半路夭折,所以要在handler里指定一个快到期时的回调:这里的task是handler的参数
task.expirationHandler = { operation.cancel() }
handler还挺麻烦的,还要提供通知系统任务已经完成的回调:
operation.completionBlock = { task.setTaskCompleted(success: !operation.isCancelled) }
最后启动这个操作:
operationQueue.addOperation(operation)
Registering and Scheduling Tasks in Extensions
Extensions can schedule a task, such as the update of a machine learning model. Register a task scheduled by extensions in the main app. The system launches the app to run the task.
这里的Extensions 是什么呢?哪位兄弟知道的留个言吧,谢谢🙏