我试图在函数内部发出MKDirections请求,然后返回该值。
这就是我目前所拥有的
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
}
我知道MKDirections是异步运行的,所以当前在directions请求完成之前返回。如何使return语句等待某种完成处理程序?
同时也意识到这个问题在这里的答案相当模糊,非常笼统。我一直不知道如何把这个答案应用到这个具体的问题上。
最佳答案
可以添加完成处理程序以传递可选字符串和错误,如下所示:
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)
}
}
使用
requestETA(userCLLocation: location, coordinate: coordinate) { (travelTime, error) in
guard let travelTime = travelTime, error == nil else { return }
print(travelTime)
}
关于swift - MKDirections computeWithCompletionHandler,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44533592/