【发布时间】:2015-03-23 19:44:24
【问题描述】:
我正在尝试使用 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 是异步的。您的 return 语句将在 reverseGeocodeLocation 完成之前在主线程上执行。
-
有没有简单的方法解决这个问题?我试过直接从 CLGeocoder() 返回,但它告诉我我不能返回一个字符串,因为它是无效的。我玩过并试图告诉它返回一个字符串,但它显然也不喜欢那样。谢谢。
-
您应该为您的函数 getPlaceName 设置一个完成块,并通过该块传递答案,而不是尝试使用 return 语句
-
我发布了一个使用完成块制作函数的示例
标签: swift clgeocoder