1. 程式人生 > >程式進入後臺執行NSTimer

程式進入後臺執行NSTimer

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

*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}中新增後臺應用配置

(注:此處程式碼片只涉及配置)

- (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">
6>在程式已經進入後臺時進行如下操作
<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;
            }
        });
    });
}
}