#import "AppDelegate.h"
@interface AppDelegate ()
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property(nonatomic,assign)NSInteger tep;
@property (nonatomic, strong) NSTimer *myTimer;
@end
- (void)applicationDidEnterBackground:(UIApplication *)application {
_tep = 0;
self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^( void) {
[self endBackgroundTask];
}];
// 模拟一个Long-Running Task
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f
target:self
selector:@selector(timerMethod:)
userInfo:nil
repeats:YES];
repeats:YES];
}
- (void) endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
AppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^(void) {
AppDelegate *strongSelf = weakSelf;
if (strongSelf != nil){
[strongSelf.myTimer invalidate];// 停止定时器
// 标记指定的后台任务完成
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
// 销毁后台任务标识符
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
});
}
// 模拟的一个 Long-Running Task 方法
- (void) timerMethod:(NSTimer *)paramSender{
_tep ++;
// backgroundTimeRemaining 属性包含了程序留给的我们的时间
NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining];
if (backgroundTimeRemaining == DBL_MAX){
// NSLog(@"Background Time Remaining = Undetermined %f",backgroundTimeRemaining);
NSLog(@"后台还在执行........ 这里是定时器里面..............3 秒一次");
//可以在这里持续发送请求和其他操作
if (_tep % 5 == 0) {
NSLog(@"..............一次");
}
} else {
NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[self endBackgroundTask];
}
网友评论