试图将BackgroundTasks用于iOS 13+。长期运行的操作似乎不起作用:
// in AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "foo.bar.name", using: nil) { task in
print("start!")
task.expirationHandler = {
// Not executed
print("expired!")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// Not executed
print("finish!")
task.setTaskCompleted(success: true)
}
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
BGTaskScheduler.shared.cancelAllTaskRequests()
let request = BGProcessingTaskRequest(identifier: "foo.bar.name")
request.earliestBeginDate = nil // or Date(timeIntervalSinceNow: 0) or Date(timeIntervalSinceNow: 5)...
do {
try BGTaskScheduler.shared.submit(request)
} catch let e {
print("Couldn't submit task: \(e)")
}
}我还尝试使用带有Operation的队列(为此,我对流进行了同步建模)。这也没用。一旦有些事情需要一段时间才能完成,它就会被卡住。
它不会将任何其他内容记录到控制台,没有错误,也没有过期的任务消息。它显示了长期运行操作之前的最后一条消息,仅此而已。我确认,通过存储偏好并在重新启动时对其进行检查,它不会向前推进。它不是储存的。
我将"foo.bar.name“添加到info.plist (在”允许的后台任务调度器标识符“中),并启用了用于后台获取和后台处理的功能。我正在使用iPhone 13.3.1并使用Xcode 11.4.1在iOS上进行测试。
补充说明:
发布于 2020-04-24 05:01:05
以下是几点意见:
register的结果代码。你应该确保你没有看到你的“不能提交任务”日志语句。submit调用之后立即设置了断点?这完成了两件事:- First, it makes sure you hit that line (as opposed, for example, to the `SceneDelegate` methods).
- Second, if you just pause the app manually, some random amount of time after the app has gone into background, that’s too late. It has to be in that breakpoint _immediately_ after you call `submit`. Then do `e` command. Then resume execution.
无论如何,当我这样做,运行您的代码,BGProcessingTaskRequest运行良好。我运行的是iOS 13.4.1 (和您一样,Xcode 11.4.1)。
https://stackoverflow.com/questions/61397372
复制相似问题