如何在viewDidLoad方法中引用用户当前的纬度和经度值?
我尝试过使用以下内容,但是......
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
mapView.delegate = self
let locationLong = locationManager.location!.coordinate.longitude
...
我不认为locationManager在代码运行之前有机会获取该值,并且它失败并显示消息:
致命错误:在解包可选值时意外发现nil
答案 0 :(得分:1)
我找到了我在这里寻找的答案:
Nil when obtain coordinates in swift
作为一般规则,除非启动位置服务并且已经开始进行位置更新(例如,您已经看到调用了didUpdateLocations),否则您不应期望位置属性的有效CLLocation对象。确定位置的过程是异步发生的,并且预计在viewDidLoad中不可用。应该将特定于位置的逻辑放在didUpdateLocations方法中。
答案 1 :(得分:0)
请尝试以下代码。希望这对你有用。感谢
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
mapView.delegate = self
}
// CLLocationManager Delegate Method
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
//Use manager for latitude and longitude
}