您需要使用beginBackgroundTaskWithExpirationHandler
來處理您的進程。使用此代碼。
在這裏,我呼籲來自applicationDidEnterBackground此方法:(UIApplication的*)應用程序存儲SQLite中,即使該應用程序進入後臺或UIApplicationStateInactive(按下電源按鈕)的數據。如果application.backgroundTimeRemaining變爲0,保存過程將持續10分鐘,根據IOS標準。我將發佈一個本地通知,將我的應用程序啓動到前臺以保持我的進程活着。使用此代碼並自定義您的過程。
-(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.");
}
});
}];
}
}
首先,你不能強迫你的應用程序在前臺。 – viral 2013-03-11 09:34:42
您可以將數據保存在用戶默認值中,直到數據未保存,然後清除用戶默認值 – channi 2013-03-11 09:40:59
這不僅僅是將數據保存在用戶默認值中,我將數據保存爲plist,我也使用Coredata,事情是如果用戶試圖關閉設備,我需要一個點來保存所有這些信息。 – user1708257 2013-03-11 09:45:51