gpt4 book ai didi

ios - Swift - 从反向地理编码生成地址格式

转载 作者:IT王子 更新时间:2023-10-29 08:12:55 26 4
gpt4 key购买 nike

我正在尝试在 Swift 3 中使用 CLGeocoder 生成格式化的完整地址。我提到了这个 SO线程获取下面给出的代码。

但是,有时应用程序会崩溃并在以下行显示“无”错误:

//Address dictionary
print(placeMark.addressDictionary ?? "")

问题:

  1. 如何连接从 GeoCoder 检索到的这些值以形成完整地址? (街道+城市+等)
  2. 当 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;
}

最佳答案

func getAddressFromLatLon(pdblLatitude: String, withLongitude pdblLongitude: String) {
var center : CLLocationCoordinate2D = CLLocationCoordinate2D()
let lat: Double = Double("\(pdblLatitude)")!
//21.228124
let lon: Double = Double("\(pdblLongitude)")!
//72.833770
let ceo: CLGeocoder = CLGeocoder()
center.latitude = lat
center.longitude = lon

let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude)


ceo.reverseGeocodeLocation(loc, completionHandler:
{(placemarks, error) in
if (error != nil)
{
print("reverse geodcode fail: \(error!.localizedDescription)")
}
let pm = placemarks! as [CLPlacemark]

if pm.count > 0 {
let pm = placemarks![0]
print(pm.country)
print(pm.locality)
print(pm.subLocality)
print(pm.thoroughfare)
print(pm.postalCode)
print(pm.subThoroughfare)
var addressString : String = ""
if pm.subLocality != nil {
addressString = addressString + pm.subLocality! + ", "
}
if pm.thoroughfare != nil {
addressString = addressString + pm.thoroughfare! + ", "
}
if pm.locality != nil {
addressString = addressString + pm.locality! + ", "
}
if pm.country != nil {
addressString = addressString + pm.country! + ", "
}
if pm.postalCode != nil {
addressString = addressString + pm.postalCode! + " "
}


print(addressString)
}
})

}

关于ios - Swift - 从反向地理编码生成地址格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41358423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com