我正在尝试使用MKDirections类中的calculateETAWithCompletionHandler计算Swift中两个坐标之间的ETA。我的程序中有以下代码,
MapViewController.swift
print("A")
calculateETAofClosestBus(closestBusStop)
print("B")
func calculateETAofClosestBus(destination: BusStop) {
var shortestETA = 0
print("C")
var request = MKDirectionsRequest()
var sourceItem = MKMapItem(placemark: MKPlacemark(coordinate: listBuses[0].pin.coordinate, addressDictionary: nil))
request.source = sourceItem
request.transportType = .Automobile
let destinationCoordinates = CLLocationCoordinate2D(latitude: destination.coordinate.latitude, longitude: destination.coordinate.longitude)
let destinationItem = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinates, addressDictionary: nil))
request.destination = destinationItem
request.requestsAlternateRoutes = false
var directions = MKDirections(request: request)
print("D")
directions.calculateETAWithCompletionHandler { (etaResponse, error) -> Void in
print("E")
if let error = error {
print("Error while requesting ETA : \(error.localizedDescription)")
} else {
print("F")
shortestETA = Int((etaResponse?.expectedTravelTime)!)
}
}
print("G")
}
我包含了print语句来显示代码的执行情况。当我运行程序时,我得到的输出是
A
C
D
G
B
E
F
所以,我注意到calculateETAofClosestBus()函数完成执行(到达G,然后是B),然后 directions.calculateETAWithCompletionHandler 执行,所以'E'和'F'被打印< strong> AFTER 我们从calculateETAofClosestBus()返回。
我确定我不明白calculateETAWithCompletionHandler是如何工作的,但我想通过汽车计算两个注释之间的ETA,如果有更直观的方法来完成这个或者有人可以帮我理解Handler更好,非常感谢。
解决方案:
iOS - Swift - Function that returns asynchronously retrieved value帮助我了解如何做到最好。