如何从另一个函数中侦听代理响应?

时间:2017-02-09 08:15:03

标签: ios cllocationmanager

我希望有一个名为requestData的函数,它将获取用户的当前位置,然后执行URL请求。我需要requestData-function来完成请求完成时的回调,无论是否成功。这是我到目前为止所提出的:

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。

1 个答案:

答案 0 :(得分:0)

CLLocation包含多个数据,用于检查所获得位置的准确性和时间。您可以在执行performRequest()请求之前检查此数据的准确性。

查看CLLocation的文档,然后查看下面的伪代码。在de didUpdateLocations中,您可以了解我认为可能是您的解决方案。我直接用SO写的,所以不要讨厌错误。

但基本上使用:

  

var horizo​​ntalAccuracy:CLLocationAccuracy {get}

     

var verticalAccuracy:CLLocationAccuracy {get}

     

var timestamp:Date {get}

 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}