反向地理编码在斯威夫特4
问题描述:
我试图写一个简单的方法,喂了CLLocationDegrees
并返回CLPlacemark
。看着Apple's documentation,这看起来很简单。反向地理编码在斯威夫特4
下面是我所倾倒入一个游乐场:
import CoreLocation
// this is necessary for async code in a playground
import PlaygroundSupport
// this is necessary for async code in a playground
PlaygroundPage.current.needsIndefiniteExecution = true
func geocode(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> CLPlacemark? {
let location = CLLocation(latitude: latitude, longitude: longitude)
let geocoder = CLGeocoder()
var placemark: CLPlacemark?
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if error != nil {
print("something went horribly wrong")
}
if let placemarks = placemarks {
placemark = placemarks.first
}
}
return placemark
}
let myPlacemark = geocode(latitude: 37.3318, longitude: 122.0312)
既然这样,我的方法是返回nil。我不知道我的错误在哪里,但我确信这是我的愚蠢行为。谢谢你的阅读。
答
import UIKit
import CoreLocation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) ->()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { placemarks, error in
guard let placemark = placemarks?.first, error == nil else {
completion(nil, error)
return
}
completion(placemark, nil)
}
}
用法:
geocode(latitude: -22.963451, longitude: -43.198242) { placemark, error in
guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
print("address1:", placemark.thoroughfare ?? "")
print("address2:", placemark.subThoroughfare ?? "")
print("city:", placemark.locality ?? "")
print("state:", placemark.administrativeArea ?? "")
print("zip code:", placemark.postalCode ?? "")
print("country:", placemark.country ?? "")
}
}
有关标属性的更多信息,你可以检查此CLPlacemark
这将打印
address1: Rua Casuarina
address2: 443
city: Rio de Janeiro
state: RJ
zip code: 20975
country: Brazil
geocoder.reverseGeocodeLocation是异步的,你需要一个完成处理程序 –
谢谢。我会看看我能否弄清楚。 – Adrian
我的帖子是错误的。检查我的编辑。我复制粘贴你的代码,并没有注意到你通过两个位置,而不是两个双打 –