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

热门标签

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

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

#import "HomePageViewController.h"

@interface HomePageViewController ()<AMapLocationManagerDelegate>

@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];
}];

标签:

未经允许不得转载:作者:SheaYang, 转载或复制请以 超链接形式 并注明出处 技术Dog|博客
原文地址:《iOS 一句代码让你的app进入后台后定时器仍然正常运行》 发布于2019-10-09

分享到:
赞(0) 打赏

评论 抢沙发

3 + 7 =


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

长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

Vieu4.0主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?