转自:http://blog.csdn.net/pz0605/article/details/49719207
根据苹果文档中关于后台执行的描述,任何app都有10分钟左右的后台任务执行时间。 10分钟后,app会被iOS 强行挂起。
但是,有5类app允许有“无限的”后台运行时间:
1. Audio。
2. Location/GPS。
3. VoIP。
4. Newsstand。
5. Exernal Accessory 。
你可以将任何app声明为上述5种类型以获得无限的后台运行时间,但当你提交app到App Store时,苹果会审查你的app,一旦发现你“滥用”了后台API,你的app将被拒绝。
当然,对于企业开发而言,不存在“滥用”的问题——企业app可以通过OTA部署,不经过苹果商店审查。
在企业部署中,你可以将一个app声明为VoIP,但这个程序根本和VoIP无关,我们的目的只是为了让iOS给我们无限后台执行的权限。声明过程是在app的Info.plist文件中加入以下key:
<key> UIBackgroundModes</key>
<array>
<string> voip</string>
</array>
我测试了以下代码:
- ( void )applicationDidEnterBackground:( UIApplication *)application { [self backgroundHandler ]; } - (void )backgroundHandler { NSLog(@"### -->backgroundinghandler" ); UIApplication *app = [UIApplication sharedApplication ]; bgTask = [app beginBackgroundTaskWithExpirationHandler :^{ dispatch_async(dispatch_get_main_queue(),^{ if ( bgTask != UIBackgroundTaskInvalid){ bgTask = UIBackgroundTaskInvalid; } }); NSLog(@"====任务完成了。。。。。。。。。。。。。。。===>" ); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{ while ( true ) { [HttpTool postWithPath : @"http://192.168.20.215:8080/v1/email/login" params :@{ @"email" : @"849430904@qq.com" , @"password" : @"85252" } success :^( id JSON) { NSLog(@"success:%@" ,JSON); } failure :^( NSError *error) { NSLog(@"error:%@" ,error .userInfo ); }]; sleep(5 ); } }); }
通过测试,我获得了“无限的”后台执行时间。我不知道你认为“无限”到底是多长时间,但在这个例子中,后台任务至少运行了55个小时以上,一直到我失去耐心停止测试。