iOS 长时间后台运行

2019-05-31  本文已影响0人  winsonGali
//
//  AppDelegate.m
//  backTask
//
//  Created by Winson on 2019/5/30.
//  Copyright © 2019 Winson. All rights reserved.
//

#import "AppDelegate.h"

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

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    //获取后台剩余时间
    NSTimeInterval remainTime = [[UIApplication sharedApplication] backgroundTimeRemaining];
    NSLog(@"remainTime = %.2f", remainTime);
    //开启后台任务
    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];
    if (remainTime > 0) {
        NSLog(@"remainTime = %.2f", remainTime);
    }
    _remainSeconds -= _timeInterval;
    NSLog(@"_remainSeconds = %ld", (long)_remainSeconds);
    if (remainTime <= 0) {
        self.taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            NSLog(@"xxxxx");
            [self endBackgroundUpdateask];
        }];
    }
    if (_remainSeconds <= 0) {
        [_timer invalidate];
        [self endBackgroundUpdateask];
    }
}

#pragma mark ------------------  结束后台任务 ------------------
- (void)endBackgroundUpdateask{
    [[UIApplication sharedApplication] endBackgroundTask:self.taskIdentifier];
    self.taskIdentifier = UIBackgroundTaskInvalid;
}
@end

上一篇下一篇

猜你喜欢

热点阅读