zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    边工作边刷题:70天一遍leetcode: day 95
    边工作边刷题:70天一遍leetcode: day 96-2
    边工作边刷题:70天一遍leetcode: day 96-1
    边工作边刷题:70天一遍leetcode: day 96
    边工作边刷题:70天一遍leetcode: day 97-3
    边工作边刷题:70天一遍leetcode: day 97-2
    边工作边刷题:70天一遍leetcode: day 97-1
    边工作边刷题:70天一遍leetcode: day 97
    边工作边刷题:70天一遍leetcode: day 40
    边工作边刷题:70天一遍leetcode: day 41-3
  • 原文地址:https://www.cnblogs.com/FranZhou/p/5190502.html
Copyright © 2011-2022 走看看