swift – 为什么LocationManager多次调用startUpdatingLocation
发布时间:2020-12-14 02:23:45 所属栏目:百科 来源:网络整理
导读:为什么位置管理器不止一次调用startUpdatingLocation?有时它会调用一次,有时它会调用三次.我不知道为什么;也许你可以帮助我.我有来自 GitHub的代码. import UIKitimport CoreLocationclass ViewController: UIViewController,CLLocationManagerDelegate{ le
为什么位置管理器不止一次调用startUpdatingLocation?有时它会调用一次,有时它会调用三次.我不知道为什么;也许你可以帮助我.我有来自
GitHub的代码.
import UIKit import CoreLocation class ViewController: UIViewController,CLLocationManagerDelegate { let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!,completionHandler: {(placemarks,error) -> Void in if (error != nil) { print("Error: " + error!.localizedDescription) return } if placemarks!.count > 0 { if let pm = placemarks?.first { self.displayLocationInfo(pm) } } else { print("Error with the data.") } }) } func displayLocationInfo(placemark: CLPlacemark) { self.locationManager.stopUpdatingLocation() print(placemark.locality) print(placemark.postalCode) print(placemark.administrativeArea) print(placemark.country) } func locationManager(manager: CLLocationManager,didFailWithError error: NSError) { print("Error: " + error.localizedDescription) } }
是的,这是标准行为.当您启动位置服务时,您通常会收到一系列越来越准确的CLLocation更新(即,随着时间的推移,horizo??ntalAccuracy会逐渐减少),因为设备会“预热”.例如,它可能会开始报告它可能已经基于单元塔的位置信息,但随着GPS芯片获得更多信息,它可以更好地对您的位置进行三角测量,它将为您提供更新.等等.
如果要减少此行为,可以使用较大的distanceFilter,较低的desiredAccuracy组合,或者在获得要进行地理编码的位置后调用stopUpdatingLocation. 现在你正在调用stopUpdatingLocation,但是你是从异步调用的reverseGeocodeLocation闭包中做到的.这意味着在调用reverseGeocodeLocation的完成处理程序之前,更多位置更新可以滑入.如果同步调用stopUpdatingLocation(例如在reverseGeocodeLocation之前),则会避免此行为. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |