gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:05:56 26 4
gpt4 key购买 nike

我正在构建一个应用程序,我希望每当应用程序从后台返回时跟踪更新的用户位置。

我在 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 block 并添加了以下代码

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 上并且应用程序返回到后台,那么当应用程序进入前台时,它不会刷新位置。

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

最佳答案

您应该在应用程序委托(delegate)的 didbecomeActive 方法中编写位置代码,而不是在 didFinishLaunchingWithOptions 中。尝试一下希望它会有所帮助。

关于ios - 应用程序从后台返回后位置不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com