创建一个计时器放到NSRunLoop中 修改 UIBackgroundTaskIdentifier状态
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) UIBackgroundTaskIdentifier bgTask; //用于申请后台时间
- (void)applicationDidEnterBackground:(UIApplication *)application {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(logAgain:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
UIApplication* app = [UIApplication sharedApplication];
self.bgTask = UIBackgroundTaskInvalid;
__weak __typeof (&*self)weakSelf = self;
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication]endBackgroundTask:self.bgTask];
dispatch_async(dispatch_get_main_queue(), ^{
if (weakSelf.bgTask != UIBackgroundTaskInvalid) {
weakSelf.bgTask = UIBackgroundTaskInvalid;
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (weakSelf.bgTask != UIBackgroundTaskInvalid) {
weakSelf.bgTask = UIBackgroundTaskInvalid;
}
});
}];
}
- (void)logAgain:(NSTimer*)timer{
//无限后台
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
if (self.timer != nil) {
[self.timer invalidate];
self.timer = nil;
}
}
网友评论