CLLocationManager 忽略 stopUpdatingLocation

CLLocationManager ignores stopUpdatingLocation

我在 CLLocationManager 上调用 startUpdatingLocation(),在 didUpdateLocations 方法中,当精度小于 100m 时我调用 stopUpdatingLocation(),如下所示:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var lastLocation: CLLocation = locations.last! as! CLLocation
    var accuracy = lastLocation.horizontalAccuracy

    if (accuracy < 100) {
        locationCoordinate = lastLocation.coordinate
        locationManager.stopUpdatingLocation()
        getData()
    }
}

但是didUpdateLocations方法在调用stopUpdatingLocations()之后还是会多调用一两次,除非我把locationManager设置为nil。显然,这也多次调用我的方法 getData(),这是我不想要的。如何在不将 locationManager 设置为等于 nil 的情况下使 locationManager 停止?

按照H先生上面说的,用bool就可以了。

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var lastLocation: CLLocation = locations.last! as! CLLocation
    var accuracy = lastLocation.horizontalAccuracy

    static bool flag = NO; //Or however this is done in Swift)

    if (accuracy < 100 && !flag) { //Check the flag in the condition

        locationCoordinate = lastLocation.coordinate
        locationManager.stopUpdatingLocation()
        getData()

        flag = YES; //Set flag to yes here

    }
}

我也遇到过类似的问题 issue.I 通过将 CLLocationManagerDelegate 设置为 nil

解决了这个问题