swift - 尝试将 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()
}
解决方案
我将此功能移动到应用程序中的另一个视图控制器,因为它没有在我的原始视图加载时及时设置坐标。
我也用过:
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!)")
}
推荐阅读
- regex - 奇怪的正则表达式行为,在完整的正则表达式中捕获过于贪婪,但在单独测试时正确
- ruby-on-rails - 当 STI 与连接查询一起使用时,sql 中使用了错误的类类型
- python - 结束 SELECT 事务 psycopg2 和 postgres
- julia - 为什么在 Julia 中变量和数组元素的继承方式不同?
- c# - 在 `System.Diagnostics.Process.ErrorDataReceived` 中保留特殊字符
- javascript - 如何修复 SyntaxError:await 仅在 Google Cloud Vision 的异步函数中有效
- string - 如何将引号内的所有输入转换为变量
- swift - 转换领域列表
到正常的集合或数组 - node.js - 如何定义属于与不同别名的关联
- javascript - 在 React 中更新 useState 后如何重新渲染?