在应用程序处于后台时,启动位置监控时,iOS位置更新很少发生

前端之家收集整理的这篇文章主要介绍了在应用程序处于后台时,启动位置监控时,iOS位置更新很少发生前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用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>

解决方法

来自苹果文档

If your iOS app must keep monitoring location even while it’s in the background,use the standard location service and specify the location value of the UIBackgroundModes key to continue running in the background and receiving location updates. (In this situation,you should also make sure the location manager’s pausesLocationUpdatesAutomatically property is set to YES to help conserve power.) Examples of apps that might need this type of location updating are fitness or turn-by-turn navigation apps.

似乎iOS限制后台位置更新以节省设备电源.

猜你在找的iOS相关文章