mat*_*tll 12 background cllocationmanager cllocation ios swift
我目前正在 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
}
Run Code Online (Sandbox Code Playgroud)
然后我启动以下服务:
func startLocationServices() {
// ...
locationManager.startUpdatingLocation()
locationManager.startMonitoringVisits()
locationManager.startMonitoringSignificantLocationChanges()
// ...
}
Run Code Online (Sandbox Code Playgroud)
此外,我还实现了 CLLocationManagerDelegate 方法 didChangeAuthorization()、didUpdateLocation()。
在 info.plist 文件中,我附加了以下条目:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>...</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>...</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
Run Code Online (Sandbox Code Playgroud)
在我的 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
}
Run Code Online (Sandbox Code Playgroud)
当使用此功能唤醒应用程序时,我设法获得了一些测试的连续数据,但有时应用程序在几分钟后再次暂停。
最后,我还尝试了一个计时器,每 5 分钟重新启动一次位置跟踪,但这似乎根本不影响更新持续时间。
所以我的问题是,是否有一种方法可以在后台持续接收位置更新,还是我缺少某些选项?
提前致谢。
编辑:我在 iOS 12 上测试了该应用程序,它在 5/5 测试中持续更新。所以我猜这个问题与iOS 13有关。
代码没有任何问题!!,\n我遇到了同样的问题,经过研究我发现
\n\n在 WWDC19 主题演讲中,Apple 宣布了 iOS 13 中位置权限工作方式的两项更改。第一个更改让用户可以选择与您的应用共享一次位置。这使得尝试位置功能变得更加容易,并帮助用户保持敏感位置数据的私密性。
\n\n第一个显着的变化是,即使你打电话requestAlwaysAuthorization
,用户也只会在权限对话框中获得 \xe2\x80\x98 刚才的\xe2\x80\x99 和 \xe2\x80\x98 使用时的\xe2\x80\x99 选项。如果用户授予您 \xe2\x80\x98when in use\xe2\x80\x99 权限,并且您尝试在后台扫描位置,则只会向用户显示一个对话框以授予后台权限。
因此,当用户授予WhenInUseUsage 权限时,您将always
进入CLAuthorizationStatus
,如果用户选择Allow Once
CLAuthorizationStatus
将休息到notDetermined
应用程序再次启动时
您可以查看这篇文章以获取详细信息\n https://medium.com/q42-engineering/apple-location-permission-ios13-1e0e59002889
\n\n这是视频https://developer.apple.com/videos/play/wwdc2019/705/
\n\n编辑
\n\n用户授予用户权限后,几天后,iOS 将向用户显示另一个对话框,将权限从“使用时”更改为“始终允许”。
\n\n所以现在没有办法像我们以前那样直接询问用户始终允许许可。
\n\n\n