程式進入後臺執行NSTimer
阿新 • • 發佈:2019-02-07
1>轉http://www.cnblogs.com/zzltjnh/archive/2013/05/15/3080058.html
2>info.plist - >Required background modes - > 新增App plays audio or streams audio/video using AirPlay
3>匯入系統庫 AVFoundation.framework
4>在AppDelegate.m中匯入標頭檔案 #import <AVFoundation/AVFoundation.h>
5>在- (BOOL)application:(UIApplication
(注:此處程式碼片只涉及配置)
6>在程式已經進入後臺時進行如下操作- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ NSError *setCategoryErr = nil; NSError *activationErr = nil; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr]; [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];<pre name="code" class="objc">
}<pre name="code" class="objc">- (void)applicationDidEnterBackground:(UIApplication *)application { UIApplication *app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier bgTask; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid; } }); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid; } }); }); }