MKDirections calculateWithCompletionHandler

时间:2017-06-14 00:36:19

标签: swift swift3 mkdirection

我尝试在函数内部发出MKDirections请求,然后返回该值。

这是我到目前为止所拥有的

func requestETA(userCLLocation: CLLocation, coordinate: CLLocationCoordinate2D) -> String {
    let request = MKDirectionsRequest()

    // code setting up directions request, not important or relevant

    let directions = MKDirections(request: request)

    var travelTime = "Not Available"

        directions.calculate { response, error in
            if let route = response?.routes.first {
                travelTime = "\(route.expectedTravelTime/60)"
                print(travelTime)
            } else {
                travelTime = "0"
            }
        }
    print(travelTime)
    return travelTime
}

我知道MKDirections是异步运行的,因此目前在路径请求完成之前返回。 如何让return语句等待某种完成处理程序?

同样意识到这个问题在stackoverflow以非常笼统的方式得到了相当模糊的回答。我一直无法弄清楚如何将这个答案应用于这个特定的问题。

1 个答案:

答案 0 :(得分:1)

您可以添加完成处理程序以传递可选字符串和错误,如下所示:

func requestETA(userCLLocation: CLLocation, coordinate: CLLocationCoordinate2D, completion: @escaping (_ string: String?, _ error: Error?) -> () ) {
    let request = MKDirectionsRequest()
    // code setting up directions request
    let directions = MKDirections(request: request)
    var travelTime: String?
    directions.calculate { response, error in
        if let route = response?.routes.first {
            travelTime = String(route.expectedTravelTime/60)
        }
        completion(travelTime, error)
    }
}

使用

requestETA(userCLLocation: location, coordinate: coordinate) { (travelTime, error) in
    guard let travelTime = travelTime, error == nil else { return }
    print(travelTime)
}