我目前在视图控制器中有两个字段/属性。我们正在使用calculateDirectionsWithCompletionHandler
并尝试将我的字段设置为route.distance
和route.expectedTravelTime
的值。这是代码:
func calculateDistanceAndEta(locationCoordinate: CLLocationCoordinate2D) {
let currentLocMapItem = MKMapItem.mapItemForCurrentLocation();
let selectedPlacemark = MKPlacemark(coordinate: locationCoordinate, addressDictionary: nil);
let selectedMapItem = MKMapItem(placemark: selectedPlacemark);
let mapItems = [currentLocMapItem, selectedMapItem];
let request: MKDirectionsRequest = MKDirectionsRequest()
request.transportType = MKDirectionsTransportType.Walking;
request.setSource(currentLocMapItem)
request.setDestination(selectedMapItem);
var directions: MKDirections = MKDirections(request: request);
var distsanceLabelTest = ""
var etaLabelTest = ""
directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
if (error == nil) {
if (response.routes.count > 0) {
var route: MKRoute = response.routes[0] as! MKRoute;
// route.distance = distance
// route.expectedTravelTime = eta
println("\(route.distance)")
distsanceLabelTest = "\(route.distance)"
etaLabelTest = "\(route.expectedTravelTime)"
}
} else {
println(error)
}
}
println(distsanceLabelTest)
println(etaLabelTest)
self.distanceLabelString = distsanceLabelTest
self.etaLabelString = etaLabelTest
}
但是,我们似乎无法设置任何变量,因为它只返回nil
。我们如何将我们的类字段设置为route.distance
和route.expectedTravelTime
的值。
答案 0 :(得分:1)
我们似乎无法设置任何变量,因为它只返回nil。
提供完成块的意义在于calculateDirectionsWithCompletionHandler
异步运行并在准备就绪时执行完成例程。因此,在distance
返回后,您的expectedTravelTime
和calculateDistanceAndEta
属性确实会立即保持不变,因为calculateDirectionsWithCompletionHandler
启动的进程可能尚未完成。完成后,您的完成块将会运行。如果在设置属性时需要执行某些操作,请将该代码放在完成块中。