我正在尝试使用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 ""
}
}
Run Code Online (Sandbox Code Playgroud)
除了能够从getPlaceNames()返回字符串之外,一切似乎都在起作用.我只返回以下内容:
Optional("")
Run Code Online (Sandbox Code Playgroud)
displayLocationInfo()函数似乎工作正常,因为println()出来了.所以我相信getPlaceName()函数确实从displayLocationInfo()获取了locality字符串.
有任何想法吗?谢谢.
由于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: "")
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4442 次 |
| 最近记录: |