编辑解决方案:我怀疑reverseGeocodeLocation
是异步的,所以我不得不使用
dispatch_async(
dispatch_get_main_queue(), {
self.newAddress = address
})
您还必须等到newAddress变量更新才能使用它。有一些滞后但它是典型的时间,大概是一秒钟。
ORIGINAL:
当我按下地图上的注释时,我试图使用CLGeocoder().reverseGeocodeLocation
中的字符串发送到另一个视图。但是处理程序存在于闭包及其Void in
中。我已尝试String in
,但这并不符合协议。
有没有办法可以使用闭包中的数据?
反向地理编码
func getReversedGeocodeLocation(){
CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
self.name = pm.name! + "-" + pm.thoroughfare!
}
}
else {
print("Problem with the data received from geocoder")
}
})
}
答案 0 :(得分:1)
这是你想要达到的目标吗?
func getReversedGeocodeLocation(){
CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
let myAddress = pm.name! + "-" + pm.thoroughfare!
// just pass the address along, ie
self.newAddressFromGeocode(myAddress)
}
}
else {
print("Problem with the data received from geocoder")
}
})
}
func newAddressFromGeocode(address:String) {
print(address)
// this is called from the completion handler
// do what you like here ie perform a segue and pass the string along
}
答案 1 :(得分:0)
您可以尝试这样的事情:
// add a variable outside the function. Once this is filled with the address you can pass it in your prepareForSegue
var addresssFromPlacemark = ""
func getReversedGeocodeLocation(){
CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let placemark = placemarks![0]
var line = ""
// Format placemark into a string
line.addText(placemark.name)
line.addText(placemark.subThoroughfare, withSeparator: ", ")
if placemark.subThoroughfare != nil {
line.addText(placemark.thoroughfare, withSeparator: " ")
} else {
line.addText(placemark.thoroughfare, withSeparator: ", ")
}
line.addText(placemark.locality, withSeparator: ", ")
line.addText(placemark.administrativeArea, withSeparator: ", ")
line.addText(placemark.postalCode, withSeparator: ", ")
line.addText(placemark.country, withSeparator: ", ")
self.addressFromPlacemark = line
}
}
else {
print("Problem with the data received from geocoder")
}
})
}