我正在尝试制作一个使用邮政编码的应用程序。问题是在 swift 中没有关于 Google SDK 的邮政编码相关数据解析的正确文档...我想根据生成的纬度和经度获取用户的邮政编码。
func getAddressFromLatLong(latitude: Double, longitude : Double) {
let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\
(latitude),\(longitude)&key=YOUR_API_KEY_HERE"
Alamofire.request(url).validate().responseJSON { response in
switch response.result {
case .success:
let responseJson = response.result.value! as! NSDictionary
if let results = responseJson.object(forKey: "results")! as? [NSDictionary] {
if results.count > 0 {
if let addressComponents = results[0]["address_components"]! as? [NSDictionary] {
self.address = results[0]["formatted_address"] as? String
for component in addressComponents {
if let temp = component.object(forKey: "types") as? [String] {
if (temp[0] == "postal_code") {
self.pincode = component["long_name"] as? String
}
if (temp[0] == "locality") {
self.city = component["long_name"] as? String
}
if (temp[0] == "administrative_area_level_1") {
self.state = component["long_name"] as? String
}
if (temp[0] == "country") {
self.country = component["long_name"] as? String
}
}
}
}
}
}
case .failure(let error):
print(error)
}
}
}