微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 为什么LocationManager多次调用startUpdatingLocation?

为什么位置管理器不止一次调用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之前),则会避免此行为.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐