iOS常驻后台
1、步骤一:在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];returnYES;
}
步骤三:将以下代码添加到appDelegate文件中的- (void)applicationDidEnterBackground:(UIApplication *)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;
}
});
});
}
完成以上步骤你会发现,程序进入后台后仍可运行定时器!