I'm trying to calculate the ETA between two coordinates in Swift using calculateETAWithCompletionHandler from the MKDirections class. I have the following code in my program,
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")
}
I included print statements to show the execution of the code. When I run the program, the output I get is
A
C
D
G
B
E
F
So, I've noticed that the calculateETAofClosestBus() function finishes executing (reaches G, then B), but then directions.calculateETAWithCompletionHandler executes, so 'E' and 'F' get printed AFTER we've returned from calculateETAofClosestBus().
I'm sure I don't understand how calculateETAWithCompletionHandler works, but I would like to calculate the ETA between two Annotations via an automobile and if there is a more intuitive way to accomplish this or if someone could help me understand the Handler better, that would be greatly appreciated.
Solution:
iOS - Swift - Function that returns asynchronously retrieved value helped me understand how to accomplish this best.
Please look ath this Link it clearly states
calculateETAWithCompletionHandler
works asynchronously .Since asynchronous, it works on different thread.But your main thread is executing on its own way and prints GIf you would like to return in the asynchronous method..You can do using closure.Here is the link