FrankZp FrankZp - 2 months ago 18
iOS Question

Dispatched Saving operations on applicationDidEnterBackground:

Apple's documentation of "App States and Multitasking" (Section "What to Do When Moving to the Background") say for saving when the app goes to background:


Save user data and app state information. All unsaved changes should be written to disk when entering the background. This step is necessary because your app might be quietly killed while in the background for any number of reasons. You can perform this operation from a background thread as needed.


When I start a dispatched operation e.g. for saving which takes some time at
applicationDidEnterBackground:
like the following I don't get the NSLog output when pressing the home button. After returning to the app, the NSLog output appears.

- (void)applicationDidEnterBackground:(UIApplication *)application {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self performOperation];
NSLog(@"Operation finished");
});
}


Can I be sure that the
performOperation
method was performed completely or did it interrupt when the app entered sleep mode?

Answer

Make sure that you have the plist key setting UIApplicationExitsOnSuspend set to no to ensure applicationDidEnterBackground is called.

Next make sure you start a long running task. In your case it would look like this:

- (void)applicationDidEnterBackground:(UIApplication *)application {
   UIBackgroundTaskIdentifier __block bgTask = nil;
   UIApplication  *app = [UIApplication sharedApplication];
   bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
         [app endBackgroundTask:bgTask]; 
         bgTask = UIBackgroundTaskInvalid;
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self performOperation];
         NSLog(@"Operation finished");
     });
 }

That way you have told the app to hang around for 10 minutes while you finish up. At the end of ten minutes the expiration handler is called.

In addition you can set the required background mode keys to get more time. There are a number of hacks and variations on this that can get you more time using the stuff I mentioned above.

Comments