美文网首页
iOS-无限时后台

iOS-无限时后台

作者: linbj | 来源:发表于2018-02-24 22:45 被阅读14次

    创建一个计时器放到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;
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS-无限时后台

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