首页 > 解决方案 > 尝试将 Lat 和 Long 坐标分配给变量,返回 nil

问题描述

我正在尝试从获取当前位置的函数中分配值。print 语句打印纬度和经度坐标,但变量返回为零。

我已尝试将其移至视图,但仍会出现相同的结果。

override func viewDidLoad() {
    super.viewDidLoad()
    // Ask for Authorisation from the User.
    self.locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        currentLat = locValue.latitude
        currentLong = locValue.longitude
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
    //getWeather()
    }

标签: swiftcore-location

解决方案


我将此功能移动到应用程序中的另一个视图控制器,因为它没有在我的原始视图加载时及时设置坐标。

我也用过:

locations.last?.coordinate.longitude

相对于:

guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        currentLong = locValue.longitude

我确信有更好的方法可以做到这一点,但这很有效。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        currentLong = locations.last?.coordinate.longitude
        currentLat = locations.last?.coordinate.latitude
        print("locations = \(currentLong!) \(currentLat!)")
    }

推荐阅读