我试图使用Swift 3中的CLGeocoder生成格式化完整地址。我参考了这个SO线程以获取以下代码。但是,有时应用程序会在以下行出现'nil'错误而崩溃:
//Address dictionary
print(placeMark.addressDictionary ?? "")
问题:
- 我该如何连接从GeoCoder检索的这些值以形成完整的地址?(街道+城市+等等)
- 当该函数无法找到地址时,我该如何处理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;
}