0

我正在尝试在函数内部发出 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中得到了相当模糊的回答。我一直无法弄清楚如何将该答案应用于这个特定问题。

4

1 回答 1

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)
}
于 2017-06-14T02:33:20.690 回答