应用程序在iOS上输入后台时继续操作 [英] Continue operation when app did enter background on iOS

查看:94
本文介绍了应用程序在iOS上输入后台时继续操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中我有一些NSOperation从在线数据库更新一些核心数据元素,有时更新需要一分钟,当iPhone屏幕锁定时,应用程序进入后台模式,此更新停止,所以我必须重新打开应用程序继续更新,所以我搜索了大量的堆栈溢出,我找到了一些信息:

in my app i have some NSOperation that update some core data element from a online database, sometime the update require some minute, and when the screen of iPhone lock, the app enter in the background mode, and this update is stopped, so i have to reopen the app to continue the update, so i have search a lot on stack overflow and i have find some information about:

beginBackgroundTaskWithExpirationHandler

这是苹果的一种方法,当应用程序进入时,它也会继续执行某项任务后台模式,我这样做:

that is a method from apple that let continue some task also when the app is in the background mode, and i have do this:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

UIApplication  *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask;

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
}];
}

现在应用程序在后台继续执行任务,似乎一切正常很好,所以我的问题是,我使用这种方法是安全的吗?还是有更好的模式?

and now the app continue the task in the background, and seems that all works fine, so my question is, this method i use is safe? or there is a better mode?

谢谢

推荐答案

这不是你是怎么做到的您要在后台运行的任何代码都必须正确包装。这样的事情:

That's not how you do this. Any code that you want to run in the background must be wrapped properly. Something like this:

- (void)someMethodToKeepRunningInBackground {
    UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
        // Uh-oh - we took too long. Stop task.
    }];

    // Perform task here        

    if (taskId != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:taskId];
    }
}

你在<$ c中没有做任何事情$ c> UIApplicationDelegate applicationDidEnterBackground:方法。

任何包含在后台任务调用中的任务都将被允许继续运行应用程序进入后台。

Any task that is wrapped inside the "background task" calls will be allowed to keep running when the app enters the background.

这是非常重要的部分 - 任务最多只能达到10分钟。如果它在10分钟后仍在运行,您的应用将被终止。在不正确地终止应用程序之前,到期处理程序会让您在几秒钟内干净地结束任务。

Here's the really important part - the task only gets 10 minutes maximum. If it is still running after 10 minutes your app will be terminated. The expiration handler gives you a few seconds to cleanly end the task before the app is terminated uncleanly.

这篇关于应用程序在iOS上输入后台时继续操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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