我試圖在Swift 8中使用CLGeocoder生成格式化完整地址。我參考了SO線程獲取下面給出的代碼。Swift - 從反向地理編碼生成地址格式
但是,有時應用程序崩潰,在該行一個「零」的錯誤:
//Address dictionary
print(placeMark.addressDictionary ?? "")
問題:
- 我如何可以連接地址解析器中檢索這些值來形成完整地址? (街道+城市+等)
- 如何處理當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;
}
和最後的打印地址字符串。你有你的整個地址 –
有這個問題。在等待地址從LatLng處理之前,func經歷這個過程。因此,我最終得到一個空字符串 – Dinuka
@RickGrimesLikesWalkerSoup檢查我在我的項目中使用的整個方法。你也可以使用它 –