I'm attempting to make an MKDirections request inside of a function and then return that value.
This is what I have so far
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
}
I'm aware MKDirections runs asynchronously and so currently this returns before the directions request has finished. How would I make the return statement wait for some sort of completion handler?
Also aware this question has been answered rather vaguely here stackoverflow in a very general way. I've been unable to figure out how to apply that answer to this specific problem.
You can add a completion handler to pass an optional string and an error as follow:
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)
}
}
usage
requestETA(userCLLocation: location, coordinate: coordinate) { (travelTime, error) in
guard let travelTime = travelTime, error == nil else { return }
print(travelTime)
}