IOS 後台無限執行任務
找到一些關於ios後台可以繼續執行任務的相關代碼,分享一下:
首先需要配置Info-Plist檔案,在裡面建立一個Required background modes。這個是一個數組,在下面添加如下內容:
App provides Voice over IP services(VOIP)
App plays audio or streams audio/video using AirPlay(audio)
App processes Newsstand Kit downloads(newsstand-content)
App communicates using CoreBluetooth(bluetooth-central
)
App shares data using CoreBluetooth(bluetooth-peripheral
)
App registers for location updates(location)
添加完成後,在- (void)applicationDidEnterBackground:(UIApplication *)application裡面添加如下代碼
- __block UIBackgroundTaskIdentifier background_task;
- background_task = [application beginBackgroundTaskWithExpirationHandler:^ { [application endBackgroundTask: background_task];
- background_task = UIBackgroundTaskInvalid; }];
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- while(TRUE) {
- [NSThread sleepForTimeInterval:1];
- //編寫執行任務代碼
- }
- [application endBackgroundTask: background_task]; background_task = UIBackgroundTaskInvalid;
- });