ios - 当应用被用户杀死时如何重新启动位置更新?
问题描述
即使应用程序在后台,我也在尝试获取用户位置。
该应用程序也始终具有位置权限。
它运行良好,应用程序在后台,但是当用户杀死应用程序时它不起作用。
我正在使用这个startMonitoringSignificantLocationChanges来获取位置
locationManager?.startMonitoringSignificantLocationChanges()
locationManager?.allowsBackgroundLocationUpdates = true
但是手机重启后,即使app没有运行,位置更新也能正常工作。只有当应用程序被用户在任务中杀死时,它才不起作用。
func applicationDidEnterBackground(_ application: UIApplication) {
Log.debug("Did Enter Background")
self.locationManager?.stopMonitoringSignificantLocationChanges()
self.locationManager = CLLocationManager()
self.locationManager?.delegate = self
self.locationManager?.requestAlwaysAuthorization()
self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager?.distanceFilter = 500
self.locationManager?.activityType = CLActivityType.otherNavigation
self.locationManager!.allowsBackgroundLocationUpdates = true
self.locationManager?.pausesLocationUpdatesAutomatically = false
self.locationManager?.startMonitoringSignificantLocationChanges()
}
解决方案
我刚刚通过使用allowDeferredLocationUpdates解决了这个问题
func applicationWillTerminate(_ application: UIApplication) {
Log.debug("Will Terminate")
self.locationManager?.stopMonitoringSignificantLocationChanges()
self.locationManager?.allowDeferredLocationUpdates(untilTraveled: 5, timeout: 60000)
self.locationManager?.startMonitoringSignificantLocationChanges()
}
推荐阅读
- google-bigquery - 运行 BigQuery 的 DDL“ALTER TABLE ADD COLUMN”是否收费?
- html - 如何在 HTML 中创建预期的按钮?
- twitter-bootstrap - 带有滚动内容的 Bootstrap 5 固定高度容器
- matlab - 如何在 matlab 中将 2-D 单元阵列转换为 3-D 单元阵列
- java - 动作不能转换为类 java.lang.String
- autodesk-forge - 如何解释来自 Forge Automation API 的此错误消息?
- android - 当我使用风味时,如何构建原始版本/调试版本?有没有办法为每种口味创建文件夹?& 一次构建所有类型?
- python - 为什么我的可以直接运行的代码添加%timeit后运行失败并提示ValueError?
- flutter - 在 Flutter 中循环遍历列表数据
- laravel - 如何检查 Laravel 查询中哪个条件有数据