我目前正在测试iOS 13中的背景位置模式,因为我想在后台跟踪用户的位置和运动(使用CMMotionManager)。因此,我有自己的(单例)类来处理位置跟踪。我通过以下方式初始化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()。
在.plist文件中,我添加了以下条目:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>...</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>...</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
在我的视图控制器中,我称为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有关。
代码没错! ,我也遇到过同样的问题,经过研究,我发现
在WWDC19主题演讲中,Apple宣布了对位置权限在iOS 13中的工作方式的两项更改。第一个更改使用户可以选择与您的应用共享一次位置。这样可以更轻松地试用位置功能,并帮助用户将敏感位置数据保密。
[第一个值得注意的变化是,即使您调用requestAlwaysAuthorization
,用户也只会在权限对话框中获得“立即”和“使用中”选项。如果用户授予您“使用时”权限,并且您尝试在后台扫描位置,则仅会向用户显示一个对话框,以授予背景权限。
因此,当用户授予WhenInUseUsage权限时,您将在always
中获得CLAuthorizationStatus
,如果用户选择Allow Once
,则当应用再次启动时,CLAuthorizationStatus
将恢复为notDetermined
您可以查看此文章以获取详细信息https://medium.com/q42-engineering/apple-location-permission-ios13-1e0e59002889