在应用程序处于后台时,启动位置监控时,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 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...