您需要使用beginBackgroundTaskWithExpirationHandler
来处理您的进程。使用此代码。
在这里,我从 applicationDidEnterBackground:(UIApplication *)application 调用此方法以将数据存储在 SQlite 中,即使应用程序进入后台或 UIApplicationStateInactive(按电源按钮)。如果 application.backgroundTimeRemaining 为 0,则根据 IOS 标准,保存过程将持续 10 分钟 使用此代码并自定义您的流程。
-(void)handleBackgroundSavingingProcess:(UIApplication *)application
{
NSLog(@"background task remaining time before background %f",application.backgroundTimeRemaining);
if ((([application applicationState] == UIApplicationStateBackground) || ([application applicationState] == UIApplicationStateInactive)) && [application respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)])
{
self.bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
NSLog(@"background task remaining time in expiration handler %f",application.backgroundTimeRemaining);
dispatch_queue_t concurrentQueue;
if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0)
concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0UL);
else
concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0UL);
if (concurrentQueue == nil)
return;
dispatch_async(concurrentQueue, ^{
if (self.bgTaskId != UIBackgroundTaskInvalid){
NSLog(@"background task remaining time in dispatch queue %f",application.backgroundTimeRemaining);
NSLog(@" Downloading status %d",self.isDownloadingInComplete);
if(self.isDownloadingInComplete)
{
[application presentLocalNotificationNow:localNotification];
NSLog(@"Local notification fired.");
}
[DataManager managedObjectContext] save:nil];
[application endBackgroundTask:self.bgTaskId];
self.bgTaskId = UIBackgroundTaskInvalid;
NSLog(@"Initialization invalid.");
}
});
}];
}
}