gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:16:46 25 4
gpt4 key购买 nike

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

有什么想法吗?谢谢。

最佳答案

由于 reverseGeocodeLocation 是一个异步函数,您需要让您的 getPlaceName 函数通过 block 而不是 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: "")
}
})

}

关于swift - Swift 中的 CLGeocoder - 使用 reverseGeocodeLocation 时无法返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com