iOS 一句代码让你的app进入后台后定时器仍然正常运行

这种可以用在类似于程序进入后台后需要间隔几分钟给后台发送一次位置的情况

#import "HomePageViewController.h"

@interface HomePageViewController ()

@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"打卡";
    self.view.backgroundColor = [UIColor brownColor];
    [self setupView];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    //   定位超时时间,最低2s,此处设置为2s
    self.locationManager.locationTimeout =5;
    //   逆地理请求超时时间,最低2s,此处设置为2s
    self.locationManager.reGeocodeTimeout = 5;

}

- (void)startTimer {
    
//    进入后台后使定时器持续运行
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication]endBackgroundTask:UIBackgroundTaskInvalid];
    }];
    
    self.timer = [NSTimer timerWithTimeInterval:600 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction {

    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed) {
                return;
            }
        }
        if (regeocode) {
            NSLog(@"reGeocode:%@", regeocode);
        }
    }];
    
}

- (void)stopTimer {
    if (_timer) {
        [_timer invalidate];
         _timer = nil;
    }
}

- (void) setupView {
    NSArray *titleArr = [NSArray arrayWithObjects:@"打卡上班",@"打卡下班", nil];
    for (int i = 0; i < 2; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor redColor];
        btn.center = CGPointMake(SCREEN_WIDTH/2, 100 + 100*i);
        btn.bounds = CGRectMake(0, 0, 100, 50);
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        [self.view addSubview:btn];
    }
}

- (void) btnClick:(UIButton *) sender {
    if (0 == sender.tag) {
        
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            if (error) {
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                if (error.code == AMapLocationErrorLocateFailed) {
                    return;
                }
            }
            if (regeocode) {
                NSLog(@"reGeocode:%@", regeocode);
            }
        }];
        
        [self startTimer];
        
    } else {
        kLog(@"计时器停止");
        [self stopTimer];

    }
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    
    kLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    if (reGeocode) {
        kLog(@"reGeocode:%@", reGeocode);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

主要代码还是一句话

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
     [[UIApplication sharedApplication]endBackgroundTask:UIBackgroundTaskInvalid];
}];

你可能感兴趣的:(iOS 一句代码让你的app进入后台后定时器仍然正常运行)