2016-07-14 71 views
-2

如何在viewDidLoad方法中引用用戶當前的緯度和經度值?ViewDidLoad中用戶lat long

我使用以下嘗試,但...

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有機會代碼運行之前獲得的價值和它失敗的消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

+0

如果你不知道如何使用一個類時,你爲什麼不讀它的文檔? – Desdenova

+0

獲取用戶位置可能需要幾秒鐘,所以是的,當您嘗試訪問主線程上的值時,它是零... –

+0

您需要使用'CLLocationManager'委託方法來獲取座標,您做錯了什麼。閱讀文檔 – iphonic

回答

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 
} 
+0

感謝您的回覆。我們試圖訪問viewDidLoad方法中的lat和long值。這聽起來並不是最佳的方式,但我不知道如何在應用程序打開後立即顯示用戶指示。 –

1

我發現我在這裏尋找答案:

Nil when obtain coordinates in swift

As a general rule, you should not expect a valid CLLocation object for the location property unless location services were started and location updates have already started to come in (e.g. you've seen didUpdateLocations called). The process of determining location happens asynchronously and is not to be expected to be available in viewDidLoad. One should put location-specific logic inside the didUpdateLocations method.