【发布时间】:2016-12-28 08:49:06
【问题描述】:
我正在尝试在 Swift 3 中使用 CLGeocoder 生成一个格式化的完整地址。我参考了这个 SO 线程来获取下面给出的代码。
但是,有时应用程序崩溃并在该行出现“nil”错误:
//Address dictionary
print(placeMark.addressDictionary ?? "")
问题:
- 如何连接从 GeoCoder 检索到的这些值以形成完整地址? (街道 + 城市 + 等)
- 当 func 无法找到地址时,我如何处理 nil 错误?
完整代码:
func getAddress() -> String {
var address: String = ""
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: selectedLat, longitude: selectedLon)
//selectedLat and selectedLon are double values set by the app in a previous process
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Address dictionary
//print(placeMark.addressDictionary ?? "")
// Location name
if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
//print(locationName)
}
// Street address
if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
//print(street)
}
// City
if let city = placeMark.addressDictionary!["City"] as? NSString {
//print(city)
}
// Zip code
if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
//print(zip)
}
// Country
if let country = placeMark.addressDictionary!["Country"] as? NSString {
//print(country)
}
})
return address;
}
【问题讨论】:
-
在 swift 4.1 Xcode 9.4.1 中查看我的答案。您甚至可以获得村庄名称的详细信息。 stackoverflow.com/questions/16647996/…
-
addressDictionary 在 iOS 11 及更高版本中已弃用
标签: ios swift xcode google-maps reverse-geocoding