iOS app在被用户切换到后台的时候就会处于挂起状态,如果这时你的应用正在进行一个任务中并且需要额外的时间来完成这个任务。你可以使用UIApplication的beginBackgroundTaskWithName:expirationHandler: 或者beginBackgroundTaskWithExpirationHandler:方法来申请一些额外的时间。
调用两个方法里面的任何一个方法来延迟系统暂停你的应用,并申请额外的时间来完成未完成的任务。注意,当你完成任务后,必须调用endBackgroundTask:方法来告诉系统任务完成了,可以暂停应用了。或者,当你的应用回到前台了,就必须要结束这个任务了。
static UIBackgroundTaskIdentifier bgTask;
bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
网友评论