我想在应用进入后台时保存数据。我正在取消NSOperation并在applicationDidEnterBackground
中保存数据。但它没有完成执行。
如何在应用程序进入后台之前完成此操作?
代码:
-(void)applicationDidEnterBackground:(UIApplication *)application
{
//FUNCTION_START
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[self performSelectorOnMainThread:@selector(dispatchStateNotification:)
withObject:[NSNumber numberWithInt:666]
waitUntilDone:YES ];
// Write to core data
GWSCoreDataController *dataController = [GWSCoreDataController sharedManager];
NSError *error;
if (![dataController.managedObjectContext save:&error]) {
NSLog(@"Error while saving data to Core Data: %@", [error localizedDescription]);
}
// FUNCTION_END
}
-(void)dispatchStateNotification:(NSNumber *)value {
[[NSNotificationCenter defaultCenter] postNotificationName:APPLICATION_ENTERED_BACKGROUND_NOTIFICATION object:value];
}
答案 0 :(得分:0)
您可以开始后台任务,并进行清理工作
- (void)applicationDidEnterBackground
{
UIBackgroundTaskIdentifier bgTaskId =
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTaskId];
}];
// Start cleanup
.......
[[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
}
答案 1 :(得分:0)
我有同样的问题,不得不将保存调用放在applicationWillResignActive中 - didEnterBackground似乎没有完整的CoreData保存...
答案 2 :(得分:0)
我已按照下面的要求解决了这个问题。添加了一个标志并在循环运行,直到此标志不会变为false。一旦我的任务完成或app进入前台,我就将此标记标记为false。
// start the task asynchronously which is written into the block on new thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//this loop runs continuously while flag is YES.
while(appDidEnterBackground){
sleep(1);
}//end of while
//ends the background task.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});//end of dispatch queue