didUpdateLocations只能调用一次

时间:2018-06-04 12:52:35

标签: swift location cllocationmanager

func startLocationManager() {
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
            locationManager.startUpdatingLocation()
        }
}

获得位置授权后,我在viewDidLoad()中调用了此方法,然后开始调用func locationManager(_:, didUpdateLocations:)

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let lastLocation = locations.last!

    if lastLocation.timestamp.timeIntervalSinceNow < -5 {
        return
    }
    if lastLocation.horizontalAccuracy < 0 {
        return
    }

    var distance = CLLocationDistance(Double.greatestFiniteMagnitude)

    if let location = location {
        distance = lastLocation.distance(from: location)
    }

    if location == nil || location!.horizontalAccuracy > lastLocation.horizontalAccuracy {
        location = lastLocation
        if location.horizontalAccuracy <= locationManager.desiredAccuracy {

            stopLocationManager()

            getWeather()
        }
    } else if location == nil || distance < 1 {
        let timeInterval = lastLocation.timestamp.timeIntervalSince(location!.timestamp)
        if timeInterval > 5 {
            stopLocationManager()
            getWeather()
        }
    }
}

这就是我结束updateLocation的方式:

func stopLocationManager() {
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil
}

最后,我得到了我想要的位置数据。

但是当我想以其他方式重新获取新位置时,即它已执行locationManager.startUpdatingLocation(),但仍然无法执行func locationManager(_:, didUpdateLocations:)

我想知道如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

停止更新您的位置时,请勿设置locationManager.delegate = nil。或者,如果您这样做,请在想要再次开始获取位置更新时将其设置为自我。

答案 1 :(得分:0)

删除此

locationManager.delegate = nil