MKDirections calculateWithCompletionHandler

MKDirections calculateWithCompletionHandler

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

这是我目前所拥有的

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 是异步运行的,因此目前 returns 在路线请求完成之前。 如何让 return 语句等待某种完成处理程序?

还知道这个问题在这里 以非常笼统的方式得到了相当含糊的回答。我一直无法弄清楚如何将该答案应用于这个特定问题。

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

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)
}