Swift中的CLGeocoder - 使用reverseGeocodeLocation时无法返回字符串

时间:2015-03-23 19:44:24

标签: swift clgeocoder

我试图使用CLGeocoder返回字符串中坐标的位置。我的代码目前看起来像这样:

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 ""

}

}

除了能够从getPlaceNames()返回字符串之外,一切似乎都在起作用。我只返回以下内容:

Optional("")

displayLocationInfo()函数似乎工作正常,因为println()出来了。所以我相信getPlaceName()函数确实从displayLocationInfo()获取了locality字符串。

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:7)

由于reverseGeocodeLocation是异步函数,因此需要使getPlaceName函数通过块而不是return语句传递回复。例如:

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: "")
       }
   })

}