iOS 通常是不能在後台運行的,尤其是用戶點擊鎖屏鍵,APP進入後台,網絡立馬斷開等。如何解決這個問題呢?在APP進入後台,APP怎麼爭取一些時間來“善後”。代碼如下:注:需要定義一個屬性UIBackgroundTaskIdentifier _bgTask;該代碼可以自定義後台多長時間自動結束任務。
- (void) timerMethod:(NSTimer *)paramSender
{
/*這裡處理後台需要的邏輯,不可太長*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIDevice * device = [UIDevice currentDevice];
if([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported])
{
self.pushTimer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];
//向iOS系統,借用10分鐘(默認就是10分鐘)時間。當調用beginBackgroundTaskWithExpirationHandler: 記得必須調用endBackgroundTask:方法,否則iOS會終止你的程序.
_bgTask = [application beginBackgroundTaskWithExpirationHandler:^
{
NSLog(@"後台10分鐘運行完成,APP進程即將被掛起");
if(_pushTimer!=nil)
{
[_pushTimer invalidate];
}
[application endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}];
//如果想提前結束10分鐘的後台運行,可在下面加邏輯,目前是空轉.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSInteger remaining = [application backgroundTimeRemaining];
NSLog(@"remain %d S", remaining);
while (remaining > 30 && _bgTask != UIBackgroundTaskInvalid) {
sleep(15);
remaining = [application backgroundTimeRemaining];
NSLog(@"remain %d S", remaining);//iOS 7就只有180秒,但是超過這個時間程序依然可以運行
// if (remaining<=180) {//如果想提前結束10分鐘的後台運行,打開這個if
// [application endBackgroundTask:_bgTask];
// _bgTask = UIBackgroundTaskInvalid;
// }
}
NSLog(@"background thread finished");
});
}
}