这是内置的,功能非常丰富。
见Uploading Data to a Website
和Downloading Files in the Background 了解详细信息。 (后台文档侧重于下载,但同样的方法适用于发送。)
使用URLSessionConfiguration.background(withIdentifier:) 创建后台会话。然后你可以用它和 URLSessionUploadTask 来发送你的数据。
如果您需要在任务完成时启动并通知您,请设置sessionSendsLaunchEvents(但听起来您可能不需要)。
使用委托进行回调。您不能为此配置使用完成处理程序。
例如,创建会话(基于文档):
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "MySession")
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
如果您需要在完成后重新启动,您还需要配置您的应用委托以通过实现来处理这些启动事件:
func application(_ application: UIApplication,
handleEventsForBackgroundURLSession identifier: String,
completionHandler: @escaping () -> Void)
(请务必在提交活动后致电completionHandler!)
有关更多详细信息,请参阅 WWDC 2020 的 Background execution demystified。