【问题标题】:iOS location updates are infrequent when starting location monitoring while app is in the background当应用程序在后台启动位置监控时,iOS 位置更新很少
【发布时间】:2018-07-13 04:13:41
【问题描述】:

我有一个使用 CLLocationManager 请求位置更新的应用。当应用程序收到来自外部蓝牙设备的通知时,就会开始监控。应用程序在前台和后台都监听来自设备的通知,并且在这两种情况下都成功启动了位置更新。

如果在应用程序处于前台时开始监控,我会根据我在位置管理器上配置的距离过滤器获取位置更新。

但是,如果在应用程序处于后台时启动监控,我仍然会收到位置更新,但很少。有谁知道这是否是预期的行为,或者我是否可能错误地配置了某些东西?

代码中的设置如下:

fileprivate lazy var locationManager = CLLocationManager()

func initLocationManager(distanceFilter: CLLocationDistance = 270,
                             desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyNearestTenMeters,
                             activityType: CLActivityType = .automotiveNavigation) {
    locationManager.requestAlwaysAuthorization()
    locationManager.allowsBackgroundLocationUpdates = true
    if canGetLocationUpdate() {
        locationManager.desiredAccuracy = desiredAccuracy
        locationManager.distanceFilter = distanceFilter
        locationManager.activityType = activityType
        locationManager.delegate = self
    }
}

func startLocationMonitoring() {
    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
    } else {
        log.error("Unable to start location monitoring")
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    for location in locations {
        log.debug("Got location \(location.coordinate) with speed \(location.speed) and accuracy \(location.horizontalAccuracy)")
    }
}

Info.plist 中有以下内容:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key><string>To allow the app...</string>
<key>NSLocationAlwaysUsageDescription</key><string>To allow the app...</string>
<key>NSLocationWhenInUseUsageDescription</key><string>To allow the app...</string>
...
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>location</string>
</array>

【问题讨论】:

    标签: ios swift cllocationmanager


    【解决方案1】:

    来自苹果文档

    如果您的 iOS 应用即使在后台也必须保持监控位置,请使用标准位置服务并指定 UIBackgroundModes 键的位置值以继续在后台运行并接收位置更新。 (在这种情况下,您还应确保将位置管理器的 pausesLocationUpdatesAutomatically 属性设置为 YES 以帮助节省电量。)可能需要此类位置更新的应用示例包括健身或逐向导航应用。1234565 >

    似乎 iOS 会在后台限制位置更新以节省设备电量。

    【讨论】:

    • 谢谢,这也是我要得出的结论。仍然很想知道是否有人真的观察到了我所看到的。
    【解决方案2】:

    您的应用在后台获取的位置更新完全由 iOS 处理,不受您的应用控制。

    根据 Apple 关于后台定位服务的文档:

    启用此模式不会阻止系统暂停 应用程序,但它确实告诉系统它应该唤醒应用程序 每当有新的位置数据要交付时。因此,这个键 有效地让应用程序在后台运行以处理位置 随时更新。

    更多信息请参考Background Execution

    【讨论】:

    • 感谢您的输入@kd02,这是正确的。我真的很想看看其他人是否在他们的应用程序处于后台时开始监控,以及他们是否看到与在前台开始监控(但不一定继续)时相同的更新频率。
    • @GabrielleLittler 没问题 :) 是的,看到频率差异会很有趣,我猜它受设备、iOS 版本和电池电量的影响。
    猜你喜欢
    • 2016-08-30
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2019-04-18
    相关资源
    最近更新 更多