首页 > 解决方案 > 当应用被用户杀死时如何重新启动位置更新?

问题描述

即使应用程序在后台,我也在尝试获取用户位置。

该应用程序也始终具有位置权限。

它运行良好,应用程序在后台,但是当用户杀死应用程序时它不起作用。

我正在使用这个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()
}

标签: iosswiftlocationcore-locationterminate

解决方案


我刚刚通过使用allowDeferredLocationUpdates解决了这个问题

func applicationWillTerminate(_ application: UIApplication) {
        Log.debug("Will Terminate")
        
        self.locationManager?.stopMonitoringSignificantLocationChanges()
        self.locationManager?.allowDeferredLocationUpdates(untilTraveled: 5, timeout: 60000)
        self.locationManager?.startMonitoringSignificantLocationChanges()

}

推荐阅读