问题
I'm attempting to use CLGeocoder to return the location of coordinates in a string. My code currently looks like this:
func getPlaceName(latitude: Double, longitude: Double) -> String {
let coordinates = CLLocation(latitude: latitude, longitude: longitude)
var answer = ""
CLGeocoder().reverseGeocodeLocation(coordinates, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
println("Reverse geocoder failed with an error" + error.localizedDescription)
answer = ""
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
answer = displayLocationInfo(pm)
} else {
println("Problems with the data received from geocoder.")
answer = ""
}
})
return answer
}
func displayLocationInfo(placemark: CLPlacemark?) -> String
{
if let containsPlacemark = placemark
{
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
println(locality)
println(postalCode)
println(administrativeArea)
println(country)
return locality
} else {
return ""
}
}
Everything seems to be working, apart from being able to return the string from getPlaceNames(). I only every get the following returned:
Optional("")
The displayLocationInfo() function seems to work fine, as the println()s come out ok. So I believe that the getPlaceName() function is indeed getting the locality string from displayLocationInfo().
Any ideas? Thanks.
回答1:
Since reverseGeocodeLocation
is an asynchronous function, you need to make your getPlaceName
function pass the answer back via a block instead of a return statement. Example:
func getPlaceName(latitude: Double, longitude: Double, completion: (answer: String?) -> Void) {
let coordinates = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(coordinates, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
println("Reverse geocoder failed with an error" + error.localizedDescription)
completion(answer: "")
} else if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
completion(answer: displayLocaitonInfo(pm))
} else {
println("Problems with the data received from geocoder.")
completion(answer: "")
}
})
}
来源:https://stackoverflow.com/questions/29219004/clgeocoder-in-swift-unable-to-return-string-when-using-reversegeocodelocation