2016-02-27 17 views
0

在我的應用程序中,我需要多次用戶的位置,所以我創建了一個實用程序類來獲取座標。這不是按預期工作的,因爲我想調用一個函數來直接返回座標,但它不起作用,因爲它是異步吃飯的。我想,在我的ViewController,才能夠稱其爲單身,就像這樣:工具類在swift中返回GPS位置?

coords = GPSUtil.sharedInstance.getCoordinates() 

隨着使用下列功能:

public func getCoordinates() -> CLLocation { 
    // return the CLLocation here. 
} 

public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let latestLocation: AnyObject = locations[locations.count - 1] 
    initialLocation = latestLocation as! CLLocation 
} 

此刻我的LocationManager剛剛分配CLLocation到一個屬性,但我真的希望上述方法返回它。可以做到嗎?

回答

0

聽起來像是你應該添加一個var到您的實用工具類,像這樣:

class GPSUtil { 
    var latestLocation = CLLocation(latitude: 0, longitude: 0) //initial init 

    public func getCoordinates() -> CLLocation { 
     return self.latestLocation 
    } 

    public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

     self.latestLocation = locations[locations.count - 1] 
    } 
} 
+0

我相信我試過了,似乎它返回的位置已經dertermined過嗎?因爲調用locationManager.startUpdatingLocation()需要一段時間直到它確定。 – Recusiwe

+0

沒有看到你的代碼的其餘部分,我不能評論它爲什麼可能不工作。具體來說,我不知道你是如何調用'didUpdateLocations'的。 – sschale

+0

我相信它在調用locationManager.startUpdatingLocation()時會自動調用,並且問題似乎是,如果我只是返回之前未分配的屬性。所以我相信我必須等到propertyManager被分配到locationManager函數中,我只是不知道如何。 – Recusiwe