iOS在后臺鎖屏狀態(tài)下不能持續(xù)定位和提交位置信息的解決辦法

前情提要

公司一個項目需要用到在登錄后,鎖屏后臺的狀態(tài)下也能持續(xù)性獲取定位信息,并且每間隔20S提交到服務(wù)端。

第一步:

info.plist文件中添加如下內(nèi)容

截屏2020-08-04 16.37.59.png

或者 在TARGET --- Signing&&Capabilities --- Background Mode中勾選Location Updates,如下圖
截屏2020-08-04 16.41.41.png

第二步:

由于我用的高德地圖來獲取位置信息的,那就需要在定位前&&獲取定位權(quán)限后將AMapLocationManagerpausesLocationUpdatesAutomatically屬性設(shè)置為NO,allowsBackgroundLocationUpdates屬性設(shè)置為YES。如下

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
            _locationManager.allowsBackgroundLocationUpdates = YES;
        }
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.locationTimeout = 2;
        _locationManager.reGeocodeTimeout = 2;
    }
    return _locationManager;
}

第三部:

為了方便獲取位置信息和提交,我單獨寫了一個GCD-Timer的管理類,如下

#import "JTTimerManager.h"
#import "LocationManager.h"
static JTTimerManager *jtm = nil;

@interface JTTimerManager ()
@property (nonatomic, strong) dispatch_source_t reportTimer;
@end

@implementation JTTimerManager

/*
 創(chuàng)建單利,單利的唯一性
 */
+ (instancetype)share{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jtm = [[self alloc]init];
    });
    return jtm;
}


/*
 覆蓋該方法主要確保 alloc init方法創(chuàng)建對象的唯一性
 */
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jtm = [super allocWithZone:zone];
    });
    return jtm;
}

/*
 確保通過copy產(chǎn)生對象的唯一性
 */
- (id)copy{
    return self;
}

/*
 確保通過mutableCopy產(chǎn)生對象的唯一性
 */
- (id)mutableCopy{
    return self;
}

#pragma mark - GCD-Timer
- (dispatch_source_t )timerWithTimeInterval:(NSTimeInterval)timeInterval
                        delay:(NSTimeInterval)delay
                        block:(void (^)(void))block{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(timeInterval * NSEC_PER_SEC);
    dispatch_source_set_timer(timer, start, interval, 0);
    dispatch_source_set_event_handler(timer, ^{
        if(block){
            block();
        }
    });
    return timer;
}

#pragma mark - 啟動定時器
- (void)startWithTimer:(dispatch_source_t)timer{
    if(timer){
        dispatch_resume(timer);
    }
}


#pragma mark - 取消定時器
- (void)cancelWithTimer:(dispatch_source_t)timer{
    if(timer){
        dispatch_cancel(timer);
    }
}


#pragma mark - 計時操作
- (void)commitLocationInfo{
    NSLog(@"** 提交定位信息 **");
    [[LocationManager shared] getLocationInfoWithHandler:^(CLLocation * _Nonnull location, AMapLocationReGeocode * _Nonnull regeocode, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 開始定位并提交位置信息
+ (void)startReport{
    JTTimerManager *jtm = [JTTimerManager share];
    @WeakObj(jtm);
    jtm.reportTimer = [jtm timerWithTimeInterval:20 delay:0 block:^(void) {
        [Weakjtm commitLocationInfo];
    }];
    [jtm startWithTimer:jtm.reportTimer];
    
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication]endBackgroundTask:UIBackgroundTaskInvalid];
    }];
    
}

#pragma mark - 停止提交
+ (void)stopReport{
    JTTimerManager *jtm = [JTTimerManager share];
    [jtm cancelWithTimer:jtm.reportTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

還有一句全局最重要的話,有了它才能保證后臺運行。

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication]endBackgroundTask:UIBackgroundTaskInvalid];
}];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容