iOS开启后台任务

@interface AppDelegate ()   {
    NSTimer *_timer;
    NSInteger _remainSeconds;
    CGFloat _timeInterval;
}
@property(nonatomic, assign)UIBackgroundTaskIdentifier taskIdentifier;
@end

@implementation AppDelegate

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"进入后台");
    [self beginBackgroundUpdateTask];
    //获取后台剩余时间
    NSTimeInterval remainTime = [[UIApplication sharedApplication] backgroundTimeRemaining];
    //开启后台任务
    self.taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"后台任务即将终止");
    }];
    //10分钟
    _remainSeconds = 10 * 60;
    //开启新的后台任务时间间隔,留点时间在后台结束之前调用,保证成功率
    _timeInterval = ceil(remainTime - 5);
    //开启定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(doTimer:) userInfo:nil repeats:YES];
}

- (void)doTimer:(NSTimer *)sender {
    NSTimeInterval remainTime = [[UIApplication sharedApplication] backgroundTimeRemaining];
    _remainSeconds -= _timeInterval;
    if (remainTime <= 0) {
        self.taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [self endBackgroundUpdateask];
        }];
    }
    
    if (_remainSeconds <= 0) {
        [_timer invalidate];
        [self endBackgroundUpdateask];
    }
}

- (void)beginBackgroundUpdateTask{
    self.taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        NSTimeInterval remainTime = [[UIApplication sharedApplication] backgroundTimeRemaining];
        [self endBackgroundUpdateask];
    }];
}

- (void)endBackgroundUpdateask{
    [[UIApplication sharedApplication] endBackgroundTask:self.taskIdentifier];
    self.taskIdentifier = UIBackgroundTaskInvalid;
}

@end

你可能感兴趣的:(iOS开启后台任务)