应用程序从后台返回后位置不会更新

时间:2018-10-09 23:31:14

标签: ios swift location cllocationmanager xcode10

我正在构建一个应用程序,当该应用程序从后台返回时,我想跟踪该位置。

我在AppDelegate的didFinishLaunchingWithOptions方法中编写了位置跟踪代码

//Core Location Administration
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 70
locationManager.requestAlwaysAuthorization()
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startMonitoringVisits()
locationManager.delegate = self

由于我无法验证访问,因此我也添加了标准位置跟踪

locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()

我创建了CLLocationManagerDelegate块并添加了以下代码

extension AppDelegate: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {
        let clLocation = CLLocation(latitude: visit.coordinate.latitude, longitude: visit.coordinate.longitude)

        // Get location description
        AppDelegate.geoCoder.reverseGeocodeLocation(clLocation) { placemarks, _ in
            if let place = placemarks?.first {
                let description = "\(place)"
                self.newVisitReceived(visit, description: description)
            }
        }
    }

    func newVisitReceived(_ visit: CLVisit, description: String) {
        let location = Location(visit: visit, descriptionString: description)
        LErrorHandler.shared.logInfo("\(location.latitude), \(location.longitude)")
        UserModal.shared.setUserLocation(location)
        UserModal.shared.userLocationUpdated = Date()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first  else {
            return
        }

        locationManager.stopUpdatingLocation()

        let uL = Location(location:location.coordinate, descriptionString: "")
        LErrorHandler.shared.logInfo("\(uL.latitude), \(uL.longitude)")
        UserModal.shared.setUserLocation(uL)
        UserModal.shared.userLocationUpdated = Date()
    }
}

我添加了此代码以在应用程序进入前台时开始位置跟踪

func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        locationManager.startUpdatingLocation()
    }

如果我在ViewController上并且应用程序返回到后台,则当应用程序进入前台时,它不会刷新位置。

有人可以建议一种更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您应使用App委托的didbecomeActive方法(而不是didFinishLaunchingWithOptions)编写位置代码。尝试此希望它会有所帮助。