0
点赞
收藏
分享

微信扫一扫

Swift Apple Watch 的后台任务执行机制

Swift Apple Watch 的后台任务执行机制

官方对 WatchKit 后台任务的说明: ​​https://developer.apple.com/documentation/watchkit/running_watchos_apps_in_the_background​​

在执行后台任务的时候,系统并一定会在约定的时间执行,系统会根据系统情况统筹各个应用后台任务的执行时间。

用 ​​scheduleBackgroundRefresh​​​ 设置后台任务后,后台任务的执行是先把应用恢复到 ​​active​​​ 模式,再 ​​deactive​​​ 回非运行模式
如下:我分别在 ​​​willActive​​​ 和 ​​didDeactive​​​ 两个方法中做了两个输出到 ​​console​​ 查看打印的结果可知。

所以如果要执行后台任务,就需要避免在 ​​willActive​​ 中不必要的一些操作

定义一个后台任务

WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: Date(timeInterval: 10, since: Date()), userInfo: nil) { (error) in
if error == nil {
print("\(Date().datetimeString): background task excuted")
} else {
print(error!.localizedDescription)
}
}

console 结果

Awake From Nib:
Will Active:
Did Deactive:
2020-02-25 09:37:54: background task excuted
Will Active:
Did Deactive:
2020-02-25 09:38:04: background task excuted
Will Active:
Did Deactive:
2020-02-25 09:38:15: background task excuted
Will Active:
Did Deactive:


举报

相关推荐

0 条评论