查看 Apple 的 iOS 应用程序编程指南的后台执行部分。
UIApplication
提供一个界面来启动和结束后台任务UIBackgroundTaskIdentifier
。
在您的顶层AppDelegate
,创建一个类级别的任务标识符:
var backgroundTask = UIBackgroundTaskInvalid
现在,使用您希望完成的操作创建您的任务,并实现您的任务在过期之前未完成的错误情况:
backgroundTask = application.beginBackgroundTaskWithName("MyBackgroundTask") {
// This expirationHandler is called when your task expired
// Cleanup the task here, remove objects from memory, etc
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
// Implement the operation of your task as background task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Begin your upload and clean up JSON
// NSURLSession, AlamoFire, etc
// On completion, end your task
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}