在applicationDidEnterBackground上调度保存操作: [英] Dispatched Saving operations on applicationDidEnterBackground:

查看:142
本文介绍了在applicationDidEnterBackground上调度保存操作:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple的App States and多任务处理(移动到后台时该怎么做部分)说当应用程序转到后台时保存:

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.

当我开始调度操作时,例如对于保存需要一些时间在 applicationDidEnterBackground:如下所示我按下主页按钮时没有得到NSLog输出。返回应用程序后,出现NSLog输出。

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");
      });
}

我可以确定 performOperation 方法是完全执行还是中断了?

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

推荐答案

确保你拥有 plist 密钥设置 UIApplicationExitsOnSuspend 设置为no以确保 applicationDidEnterBackground 是叫做。

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");
     });
 }

这样你告诉应用程序在你完成时会闲逛10分钟向上。在十分钟结束时,将调用到期处理程序。

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.

这篇关于在applicationDidEnterBackground上调度保存操作:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆