程序進入后台,延遲指定時間退出
正常程序退出后,會在幾秒內停止工作;
要想申請更長的時間,需要用到
beginBackgroundTaskWithExpirationHandler
endBackgroundTask
一定要成對出現
{ NSTimer *_timer;
int aa;
__block UIBackgroundTaskIdentifier _backIden;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self beginTask];
//在非主線程開啟一個操作在更長時間內執行; 執行的動作
aa =0;
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(go:) userInfo:nil repeats:YES];
}
-(void)go:(NSTimer *)tim
{
NSLog(@"%@==%d ",[NSDate date],aa);
aa++;
if (aa==9) {
[_timer invalidate];
[self endBack]; // 任務執行完畢,主動調用該方法結束任務
}
}
-(void)beginTask
{
NSLog(@"begin=============");
_backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"begin bgend=============");
[self endBack]; // 如果在系統規定時間內任務還沒有完成,在時間到之前會調用到這個方法,一般是10分鍾
}];
}
-(void)endBack
{
NSLog(@"end=============");
[[UIApplication sharedApplication] endBackgroundTask:_backIden];
_backIden = UIBackgroundTaskInvalid;
}