【发布时间】:2020-02-04 12:43:02
【问题描述】:
UIApplication.shared.beginBackgroundTask 在 iOS 13 上无法运行。是否有任何替代方法可以在 iOS 13 上实现长时间运行的后台任务?此外,它在 iOS 12 及以下版本上也能完美运行。
当应用程序进入后台时,它会在 2 分钟内终止,而我希望它在后台继续运行数小时,因为我们正在后台进行一些处理。
以下是我正在使用的代码,这样当我的应用程序处于后台时,它可以获得额外的执行时间。我们需要额外的执行时间,因为我们定期将当前位置发送到服务器。
/// Register background task. This method requests additional background execution time for the app
private func registerBackgroundTask() {
DispatchQueue.global().async {
self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "BgTask", expirationHandler: {
// Ends long-running background task
self.endBackgroundTask()
})
}
}
/// Ends long-running background task. Called when app comes to foreground from background
private func endBackgroundTask() {
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
【问题讨论】: