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
}
URLSessionConfiguration
背景,确实更加复杂(您必须使用委托API而不是完成处理程序API;您必须使用文件API进行上传任务等),但在我看来它并不会出现错误。它是一个非常强大和宝贵的工具。我在S.O.上看到的99%的后台URL会话“问题”都是由程序员错误引起的,而不是API本身的任何“错误”。 - Rob