一. beginBackgroundTaskWithExpirationHandler
关于后台执行,任何app进入后台时,设置beginBackgroundTaskWithExpirationHandler,都有3分钟左右的后台任务执行时间。 3分钟后,app会被iOS强行挂起。
但是,有5类app允许有“无限的”后台运行时间:
1. Audio。
2. Location/GPS。
3. VoIP。
4. Newsstand。
5. Exernal Accessory 。
你可以将任何app声明为上述5种类型以获得无限的后台运行时间,但当你提交到App Store时,苹果一旦发现你“滥用”了后台API,你的app将被拒绝。
在企业部署中,你可以将一个app声明为VoIP,但这个程序根本和VoIP无关,我们的目的只是为了让iOS给我们无限后台执行的权限。声明过程是在app的Info.plist文件中加入以下key:
<key>UIBackgroundModes</key>
<array>
<string>voip</string>
</array>
测试代码:
- (void)backgroundHandler {
UIApplication* app = [UIApplicationsharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
int counter = 0;
while (1) {
NSLog(@"counter:%ld", counter++);
sleep(5);
}
});
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
BOOL backgroundAccepted = [[UIApplicationsharedApplication] setKeepAliveTimeout:600 handler:^{ [selfbackgroundHandler]; }];
if (backgroundAccepted)
{
NSLog(@"backgrounding accepted");
}
[selfbackgroundHandler];
}
注:iOS 10 上,貌似只能执行3分钟,继续研究中。
二. setKeepAliveTimeout
1.要成功调用该函数,就必须在Info.plist里设UIBackgroundModes键的array值之一voip字符串.
2.timeout必须>=600
3.唤醒后只有10秒执行时间。即handler里的代码要在10秒类执行完。10秒后app再次被阻塞。
4.该函数成功调用后,在程序生命周期内有效。
该函数的效果在回到前台的状况下,依然有效。(因此可以把它当timer使.)
5.clearKeepAliveTimeout函数用来清除handler。