Occasionally you will need to convert a callback based function to an async/await function. One example of this is below, calculating a map route appears to be only available as a callback based one. Below is an example of how to convert it to an async function. This code is actually used in Weather Driver.
func calculateSubRoute(route: MKRoute, step: MKRoute.Step) async throws -> MKDirections.Response? {
return try await withCheckedThrowingContinuation { continuation in
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: route.steps.first!.polyline.coordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: step.polyline.coordinate))
request.requestsAlternateRoutes = true
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate() { response, error in
if error != nil {
print(error)
continuation.resume(throwing: error!)
return
}
continuation.resume(returning: response)
}
}
}