[iOS]讓APP支援後臺執行
阿新 • • 發佈:2019-02-12
加入如下程式碼,你的app就可以支援後臺運行了~很簡單 #import "AppDelegate.h" static UIBackgroundTaskIdentifier bgTask; @implementation AppDelegate - (void)applicationDidEnterBackground:(UIApplication *)application { [self getBackgroundTask]; } - (void)applicationWillEnterForeground:(UIApplication *)application { [self endBackgroundTask]; } //獲取後臺任務 - (void)getBackgroundTask { NSLog(@"getBackgroundTask"); UIBackgroundTaskIdentifier tempTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ //後臺任務 }]; if (bgTask != UIBackgroundTaskInvalid) { [self endBackgroundTask]; } bgTask = tempTask; [self performSelector:@selector(getBackgroundTask) withObject:nil afterDelay:120]; } //結束後臺任務 - (void)endBackgroundTask { [[UIApplication sharedApplication] endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } @end