6

iOS 后台任务之 Long-running background task

 2 years ago
source link: https://www.isaced.com/post-258.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

iOS 后台任务之 Long-running background task

最近项目里遇到需求需要App进入后台还能执行一些任务,于是便Google了一下,整理一篇小记录。

大家都知道iOS系统里,所有App进入后台的时候默认都是会暂停所有线程,等到再双击Home键回到前台才会继续执行。那有的场景需要在后台进行upload、download,或者进行一些计算等等怎么办呢?

iOS7推出了一些新的API,让,那就是 NSURLSession ,就是为了取代前 NSURLConnection 而生,在我们常用的 AFNetworking 2.0 中也新增了对其的支持 (AFURLSessionManager/AFHTTPSessionManager) ,用 NSURLSession 可以很方便快速地进行一些后台的网络任务,很强大,网上资料也很多了,本文就不多提它了,后面也许会单独对 NSURLSession 后台任务专门写篇文章。

今天要介绍的是 long-running background task,”长时间运行后台任务”,中文应该是这个名字,当我们需要进入后台不暂停程序,就可以给系统说一声 “我需要在后台执行任务了哦~“,然后你的 App 就不会被系统挂起,准确来说是延迟暂停,注意这是全局的,意思就是 App 里所有东西都将正常执行,就跟在前台一样。不过系统给你这个权限的时间是有限的。

Begin

首先我们需要定义一个 UIBackgroundTaskIdentifier 对象,噢,Command 点进去居然是个NSUInteger

    UIBackgroundTaskIdentifier myTask;

然后有两个方法来开始后台任务,都是在 UIApplication 里,可以看到第二个方法可以传一个taskName参数,而且是iOS7新增的。(原来 iOS4.0 就支持了~) 在 Apple 的文档里是这么介绍的:

Marks the beginning of a new long-running background task.

- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void(^)(void))handler  NS_AVAILABLE_IOS(4_0);
- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(NSString *)taskName expirationHandler:(void(^)(void))handler NS_AVAILABLE_IOS(7_0);

好,那我们来开始一个后台任务:

    myTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        // 后台任务到期执行,好像是10分钟
    }];

执行上面这句话后,当你的 App 再次进入后台时就不会被马上暂停了。但是我们不能滥用这个,为了自己的App负责,也为用户的 iPhone 负责,关键是滥用的话 App Store 审核那也过不去的…

所以,有开就有关:

    [[UIApplication sharedApplication] endBackgroundTask: myTask];
    myTask = UIBackgroundTaskInvalid;

另外 UIApplication 还提供两个个属性 backgroundTimeRemainingbackgroundRefreshStatus,可自行研究…


注:关于这个时间问题,笔者也有些不解,在测试的时候 ExpirationHandler 会在 180 秒左右,也就是 3 分钟的时候触发,但后台任务还是在继续。求大神解惑!


参考文章:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK