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

2023-12-02

我正在尝试使用 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() 获取位置字符串。

有任何想法吗?谢谢。


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

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 中的 CLGeocoder - 使用verseGeocodeLocation 时无法返回字符串 的相关文章

随机推荐