【发布时间】:2015-10-04 22:14:46
【问题描述】:
我编写了以下函数来添加地图注释,该注释使用CLGeocoder() 来解析给定坐标的位置名称。我使用defer 块来获取解析的位置名称。但是,defer 块似乎在关闭完成之前完成。为什么?
下面是我的代码:
func addAnnotation(gestureRecognizer: UIGestureRecognizer) {
var locationNameStr = ""
defer {
let newPin = Pin(dictionary: locationDictionary, context: sharedContext)
newPin.name = locationNameStr
do {
//persist the new pin to core data
try sharedContext.save()
showPinOnMap(newPin)
} catch let error as NSError {
print("error saving the new pin in context")
}
}
// use CLGeocoder to resolve the location name as title of the annotation
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude), completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("reverse geocoding failed with error: \(error)")
//return
} else if placemarks!.count > 0 {
let firstPlace = placemarks![0] as CLPlacemark
if firstPlace.country != nil {
locationNameStr = "a place in \(firstPlace.country!)"
}
else if firstPlace.locality != nil {
locationNameStr = "a place in \(firstPlace.locality!)"
}
print("location name: \(locationNameStr)")
}
})
}
【问题讨论】:
-
这是正确和正确的行为。你忘了问一个问题。
标签: ios swift asynchronous deferred clgeocoder