美文网首页
iOS程序 在后台不被挂起

iOS程序 在后台不被挂起

作者: 蜗牛锅 | 来源:发表于2017-11-05 22:25 被阅读45次
#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];

}

相关文章

网友评论

      本文标题:iOS程序 在后台不被挂起

      本文链接:https://www.haomeiwen.com/subject/lwohmxtx.html