步驟一:在Info.plist中,添加"Required background modes"鍵,value為:App plays audio
步驟二:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
- // Override point for customization after application launch.
- NSError *setCategoryErr = nil;
- NSError *activationErr = nil;
- [[AVAudioSession sharedInstance]
- setCategory: AVAudioSessionCategoryPlayback
- error: &setCategoryErr];
- [[AVAudioSession sharedInstance]
- setActive: YES
- error: &activationErr];
- self.window.backgroundColor = [UIColor whiteColor];
- [self.window makeKeyAndVisible];
- return YES;
- }
複製代碼
步驟三:將以下代碼添加到appDelegate檔案中的- (void)applicationDidEnterBackgroundUIApplication
*)application函數,也可添加到在具體類中註冊的應用進入後台後的通知方法
- - (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;
- }
- });
- });
- }
複製代碼
完成以上步驟你會發現,程式進入後台後仍可運行定時器!
原文連結:http://www.cnblogs.com/zzltjnh/archive/2013/05/15/3080058.html