Dispatched Saving operations on applicationDidEnterBackground:

跟風遠走 提交于 2020-01-01 00:36:10

问题


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?


回答1:


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.




回答2:


i will use a different kind of logging just to be sure:

Flexible iOS Logging

By adding this logging to your project you can check the logs of your project regardless if you are debugging or not by going to Organizer -> Devices -> "Your device" -> console.

I think this is the best way and it has helped me a lot when i am not sure if i can debug something.



来源:https://stackoverflow.com/questions/15212672/dispatched-saving-operations-on-applicationdidenterbackground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!