我目前正在测试iOS 13的后台位置模式,因为我想要在后台跟踪用户的位置和运动(使用CMMotionManager)。 因此,我有自己的(singleton)类处理位置跟踪。我以以下方式初始化CLLocationManager:
func initializeLocationManager() -> CLLocationManager {
let manager = locationManager ?? CLLocationManager()
manager.delegate = self
manager.requestAlwaysAuthorization()
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
manager.distanceFilter = kCLDistanceFilterNone
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.activityType = .other
return manager
}
然后我启动以下服务:
func startLocationServices() {
// ...
locationManager.startUpdatingLocation()
locationManager.startMonitoringVisits()
locationManager.startMonitoringSignificantLocationChanges()
// ...
}
此外,我实现了CLLocationManagerDelegate方法didChangeAuthorization()和didUpdateLocation()。
在info.plist文件中,我添加了以下条目:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>...</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>...</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
在我的ViewController中,我调用了startLocationServices函数。目前,我将应用程序的定位数据跟踪授权设置为“ .authorizedAlways”。
大约60-130分钟后,位置更新会停止。
为解决这个问题,我已经添加了didFinishLaunchingWithOptions函数,该函数会再次触发位置更新:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let launchOptions = launchOptions,
let isLocationKey = launchOptions[UIApplication.LaunchOptionsKey.location] as? Bool,
isLocationKey {
restartServices()
}
return true
}
当使用此功能唤醒应用程序时,在某些测试中我成功获得持续的数据,但有时应用程序在几分钟后再次挂起。最后,我还尝试了一个定时器,每5分钟重新启动位置跟踪,但似乎这并不影响更新持续时间。
因此,我的问题是是否有一种方法在后台持续接收位置更新,或者我漏掉了某些选项?
先感谢你的帮助。
编辑:我在iOS 12上测试了应用程序,并在5/5个测试中获取了连续的更新。 因此,我猜问题与iOS 13有关。