gpt4 book ai didi

swift - 为什么 LocationManager 会多次调用 startUpdatingLocation?

转载 作者:搜寻专家 更新时间:2023-10-30 23:10:30 57 4
gpt4 key购买 nike

为什么位置管理器不止一次调用 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 之前),那么您将避免这种行为。

关于swift - 为什么 LocationManager 会多次调用 startUpdatingLocation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051873/

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