Я создаю приложение, в котором я хочу отслеживать обновленное местоположение пользователя всякий раз, когда приложение возвращается из фона.
Я написал свой код отслеживания местоположения в методе didFinishLaunchingWithOptions AppDelegate
//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 и в приложениивозвращается к фону, он не обновляет местоположение, когда приложение выходит на передний план.
Может кто-нибудь предложить лучший способ сделать это?