我正在研究一个计算MapView上各种坐标之间的ETA的项目.我使用异步方法calculateETAWithCompletionHandler来获取两个坐标之间的ETA,因为calculateETAWithCompletionHandler是异步的,我的代码不是线性的.
我需要我的代码是线性的,以便在TableView中显示正确的ETA信息,所以我试图在异步调用中实现一个闭包返回.但是,这仍然没有使我的代码线性化.以下是我到目前为止的情况,
override func viewDidLoad() {
var etaBetween1n2 = 0
let point1 = MKPointAnnotaion()
point1.coordinate = CLLocationCoordinate2D(latitude: 36.977317, longitude: -122.054255)
point1.title = "Point 1"
mapView.addAnnotation(point1)
let point2 = MKPointAnnotaion()
point2.coordinate = CLLocationCoordinate2D(latitude: 36.992781, longitude: -122.064729)
point2.title = "Point 2"
mapView.addAnnotation(point2)
print("A")
// Closure
calculateETA(point1, destination: point2) { (eta: Int) -> Void in
print("B")
etaBetween1n2 = eta
}
print("C")
}
// Calculates ETA between source and destination
// Makes calculateETAWithCompletionHandler call which is asynchronous
func calculateETA(source: MKPointAnnotation, destination: MKPointAnnotation, result: (eta: Int) -> Void) {
var eta = 0
let request = MKDirectionsRequest()
let sourceItem = MKMapItem(placemark: MKPlacemark(coordinate: source.coordinate, addressDictionary: nil))
request.source = sourceItem
request.transportType = .Automobile
let destinationItem = MKMapItem(placemark: MKPlacemark(coordinate: destination.coordinate, addressDictionary: nil))
request.destination = destinationItem
request.destination = destinationItem
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculateETAWithCompletionHandler { (etaResponse, error) -> Void in
if let error = error {
print("Error while requesting ETA : \(error.localizedDescription)")
} else {
eta = Int((etaResponse?.expectedTravelTime)!)
result(eta: eta)
}
}
}
我希望封闭会通过打印使我的代码成为线性,
A
B
C
但它仍然打印,
A
C
B
我是否错误地实现了闭包,或者闭包是错误的方法吗?
最佳答案 所以闭包是一个回调,这意味着它在调用该函数后继续运行代码的其余代码,然后一旦准备就会运行回调函数.
所以,如果你想在完成之后做一些事情,那么你会把它放在回调中,所以你把print(“B”)放在哪里
如果你可以计算一些东西,你的代码不应该是线性的,因为它会冻结主线程,并且在动作完成之前屏幕会变得无响应.
你想做什么?