iOS默认是不支持程序的后台运行的,可是也提供了一些途径来使得程序能后在切入后台时也正常工做。git
其中抛开常见的后台音乐等擦边球手段,比较正规的就是声请一个后台任务,可是任务的执行时间被限制为10分钟,而且在10分钟以后再次声请也不会成功。github
本文采用的手段就是在声请10分钟的任务时间到达时利用一个while(true)将当次runloop挂起等待程序切回时再跳出。app
核心代码以下oop
声请后台任务spa
1 UIApplication *application = [UIApplication sharedApplication]; 2 __block UIBackgroundTaskIdentifier background_task; 3 //Create a task object 4 background_task = [application beginBackgroundTaskWithExpirationHandler: ^ { 5 [self hold]; 6 [application endBackgroundTask: background_task]; 7 background_task = UIBackgroundTaskInvalid; 8 }];
hold住限时任务结束时的runloopcode
1 - (void)hold 2 { 3 _holding = YES; 4 while (_holding) { 5 [NSThread sleepForTimeInterval:1]; 6 /** clean the runloop for other source */ 7 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE); 8 } 9 }
以后做者发现不须要先声请10分钟限时后台任务,直接在程序切出后台时挂起一个while(true)就能够达到相同的效果。blog
实验证实不申请后台task程序虽然会执行,可是切出去后返回没法正常显示UI。get