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.