swift - didUpdateLocations 只能调用一次

标签 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:).

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

最佳答案

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

关于swift - didUpdateLocations 只能调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50681105/

相关文章:

ios - UIView 可以为自己分配一个 UITapGestureRecognizer 吗?

ios - 在 ios 中使用 Alamofire 在 collectionView 中显示图像

ios - LeftBarButtonItem 位置不正确

ios - 如何将 Base64 字符串转换为 NSData?

PHP 301 重定向位置 URI 格式

http - 哪个浏览器不能使用 header 位置重定向?

php - 文档引用位置 javascript 远程 php 服务器

ios - 使用 I-Beacon 的室内导航

iphone - CL位置管理器

iphone - 监控重大位置变化的 iOS 应用程序是否会在设备重启时重新启动?