尝试将 Lat 和 Long 坐标分配给变量,结果为 nil



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

我尝试将其移动到视图将出现,但结果仍然相同。

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()
}

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

我还使用了:

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!)")
}

最新更新