iOS 後台運行一段時間(不是地圖,音樂類型APP)
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"); }); }}