didUpdateLocations 委托方法重复随机次数

didUpdateLocations delegate method is repeated a random number of times

我在我的方法 didUpdateLocations 中获取了用户的纬度和经度。如果允许位置,我调用一个方法,该方法接受参数纬度、经度并调用 web 服务,否则我显示一个 UIAlertView。

问题是:iOS 随机调用了我的 locationManager 委托方法。所以我的网络服务被调用了好几次...请问我该如何解决?

当我调用该位置时,验证是否允许...我在上一个屏幕中提出请求:

    // GET LOCATION
    self.initializeWaitingScreen()
    if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.startUpdatingLocation()
    } else {
        let loginFailAlert: UIAlertView = UIAlertView(title: "Localisation refusée", message: "Vos fonctionnalités sont restreintes, pour accéder à l'application complète, veuillez activer la localisation", delegate: self, cancelButtonTitle: "OK")
        loginFailAlert.show()
        self.initializeUIComponent()
        self.initializeDataWithWebServiceWithoutLocation()
    }

我的 locationManager 方法:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
            var lon = manager.location.coordinate.longitude.description
            var lat = manager.location.coordinate.latitude.description
            self.locationManager.stopUpdatingLocation()
            self.initializeDataWithWebServiceWithLocation(lon, _lat: lat)
            self.initializeUIComponent()
}

self.initializeDataWithWebServiceWithLocation(lon, _lat: lat) 获取经度和纬度,并将其提供给我调用 webservices 的方法。

这是预期的行为。当 CLLocationManager 确定用户的位置时,将发送更新(我的意思不仅仅是显而易见的)。请参阅 Apple's docs 的摘录:

Regardless of which location service you use, location data is reported to your app via the location manager’s associated delegate object. Because it can take several seconds to return an initial location, the location manager typically delivers the previously cached location data immediately and then delivers more up-to-date location data as it becomes available. Therefore it is always a good idea to check the timestamp of any location object before taking any actions. If both location services are enabled simultaneously, they deliver events using the same set of delegate methods.

如果您需要对事件进行一些过滤,则需要 (1) 确保已正确设置 desiredAccuracy 以帮助最大程度地减少事件数量,然后 (2) 执行任何特定于应用程序的特定过滤。不过要小心,因为您获得多个更新的原因是确定的位置已更改。如果您事后猜测系统,您可能会得到不准确的数据。

最后,评估您是否需要位置更改或重大位置更改。如果不需要高粒度,请使用 "significant".