iOS9 后台定位


 原文地址: https://github.com/ChenYilong/iOS9AdaptationTips

 

【iOS9在定位的問題上,有一個壞消息一個好消息】壞消息:如果不適配iOS9,就不能偷偷在后台定位(不帶藍條,見圖)!好消息:將允許出現這種場景:同一App中的多個location manager:一些只能在前台定位,另一些可在后台定位,並可隨時開啟或者關閉特定location manager的后台定位。

如果沒有請求后台定位的權限,也是可以在后台定位的,不過會帶藍條:enter image description here

如何偷偷在后台定位:請求后台定位權限:

 // 1. 實例化定位管理器
_locationManager = [[CLLocationManager alloc] init];
// 2. 設置代理
_locationManager.delegate = self;
// 3. 定位精度
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
// 4.請求用戶權限:分為:⓵只在前台開啟定位⓶在后台也可定位,
//注意:建議只請求⓵和⓶中的一個,如果兩個權限都需要,只請求⓶即可,
//⓵⓶這樣的順序,將導致bug:第一次啟動程序后,系統將只請求⓵的權限,⓶的權限系統不會請求,只會在下一次啟動應用時請求⓶
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
    //[_locationManager requestWhenInUseAuthorization];//⓵只在前台開啟定位
    [_locationManager requestAlwaysAuthorization];//⓶在后台也可定位
}
// 5.iOS9新特性:將允許出現這種場景:同一app中多個location manager:一些只能在前台定位,另一些可在后台定位(並可隨時禁止其后台定位)。
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
    _locationManager.allowsBackgroundLocationUpdates = YES;
}
// 6. 更新用戶位置
[_locationManager startUpdatingLocation];

  

但是如果照着這種方式嘗試,而沒有配置Info.plist,100%你的程序會崩潰掉,並報錯:

*** Assertion failure in -[CLLocationManager setAllowsBackgroundLocationUpdates:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreLocationFramework_Sim/CoreLocation-1808.1.5/Framework/CoreLocation/CLLocationManager.m:593

  

這個問題,有兩種方式可以解決:

第一種:

要將 Info.plist 配置如下: enter image description here

對應的 Info.plist 的XML源碼是:

<key>NSLocationAlwaysUsageDescription</key>
<string>微博@iOS程序犭袁 請求后台定位權限</string>

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

  

第二種:

在對應 target 的 Capabilities -> Background Modes -> 開啟 Location Updates

enter image description here

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM