(void)applicationWillResignActive:(UIApplication *)application {
NSLog(@" to background");
UIApplication * app = [UIApplication sharedApplication];
//请求在后台运行的权限。提供一个 //过期处理程序,以防任务运行很长时间。 NSAssert(bgTask == UIBackgroundTaskInvalid,nil);
bgTask = [app beginBackgroundTaskWithExpirationHandler:^ { //在主线程上同步清理调用以防万一 //任务实际上大约在同一时间结束。 dispatch_async(dispatch_get_main_queue(),^ {
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
//启动长时间运行的任务并立即返回。 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
// Do the work associated with the task.
[self performSelector:@selector(hai) withObject:nil afterDelay:30];
NSLog(@"App staus: applicationDidEnterBackground");
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
}