2017-02-09 48 views
0

我想要一個名爲requestData的函數,它將獲取用戶的當前位置,然後執行URL請求。我需要requestData函數在請求完成時有回調,不管它是否成功。這是我想出迄今:如何偵聽來自其他功能的代表響應?

requestData(_ completion:@escaping()->()){ 
    self.locationManager.requestLocation() 
    // Wait for the location to be updated 
    let location:CLLocation? = //myLocation 
    self.performRequest(with: location, completion: completion) 
} 
func performRequest(with location:CLLocation?, completion:@escaping()->()){ 
    //Does the URL-request, and simply calls completion() when finished. 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    if let location = locations.first {//Success} 
    else{//Error} 
} 
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) 
{//Error} 

我的想法是調用的RequestData,它將請求myLocation,然後調用performRequest。但CLLocationManager使用委託回調而不是塊來執行requestLocation。我應該怎麼做? 一切會一直很大,如果requestLocation會一直是這樣的:

self.locationManager.requestLocation({ (locations, error) in 
    if locations {} 
    else {} 
}) 

但它不是..

爲了澄清,這是一個小部件(TodayExtension)的代碼,其中,按照我的理解,需要回調,因爲我需要widgetPerformUpdate(completionHandler:)在觸發它自己之前等待我自己的completionHandler。

+0

您可以使用CLLocation並檢查該位置的時間和準確性在調用performRequest()之前獲得。這樣你就知道這個位置是儘可能準確和更新的。 – Starlord

+0

您可以將回調處理程序保存在屬性中,然後從委託方法調用它 – Paulw11

回答

0

CLLocation包含幾個數據來檢查您獲得的位置的準確性和時間。對於您來說,解決方案可能是在執行請求執行請求()之前檢查此數據的準確性。

查看CLLocation的文檔,看看我下面的僞代碼。在didUpdateLocations中,您可以瞭解我認爲可能是您的解決方案。我直接在SO中編寫它,所以不要憎恨錯誤。

但基本上使用:

VAR horizo​​ntalAccuracy:CLLocationAccuracy {得到}

VAR verticalAccuracy:CLLocationAccuracy {得到}

VAR時間戳:日期{得到}

let location:CLLocation? //myLocation 

func requestData(){ 
    self.locationManager.requestLocation() 
    // Wait for the location to be updated 

} 
func performRequest(with location:CLLocation?, completion:@escaping()- >()){ 
//Does the URL-request, and simply calls completion() when finished. 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
if let location = locations.first { 
    //When the location is accurate enough we can call 
    //the performRequest() 

    if location.horizontalAccuracy < 15 && location.timestamp > (Date().timestampSince1970 - 60){ 
     //Accurate enough?? Then do the request 
     self.performRequest(with: location, completion: completion) 

    }else{ 
     //Not accurate enough...wait to the next location update 
    } 

} 
else{//Error} 
} 
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) 
{//Error} 
相關問題