如何使用swift中的CoreLocation从英国邮政编码获取自治区?
有人知道我是否可以使用CoreLocation框架从英国邮政编码中获得自治区吗?在下面列出的函数中,不会返回自治区。它应该返回塔楼哈姆雷特如何使用swift中的CoreLocation从英国邮政编码获取自治区?,swift,core-location,Swift,Core Location,有人知道我是否可以使用CoreLocation框架从英国邮政编码中获得自治区吗?在下面列出的函数中,不会返回自治区。它应该返回塔楼哈姆雷特 func getLocationFrom(postalCode : String){ let geocoder = CLGeocoder() geocoder.geocodeAddressString(postalCode) { (placemarks, error) -> Void in let
func getLocationFrom(postalCode : String){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(postalCode) {
(placemarks, error) -> Void in
let placemark = placemarks?[0]
print("placemark.addressDictionary are \(placemark.addressDictionary)") //does not print Canary Wharf
}
}
print(getLocationFrom(postalCode:"E14 9LR")) //does not print Tower Hamlets, it prints London, which is the city, not the borough..
为了从邮政编码中获取位置信息,您只需为
placemarks
数组下标,然后访问所需索引XPath处元素的属性locality
。我的错误是,我试图访问placemarks
数组上的另一个属性,即addressDictionary
,它没有产生预期的结果
func getLocationFrom(postalCode: String, callback: @escaping(_ locality: String?) -> Void){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(postalCode) {
(placemarks, error) -> Void in
callback(placemarks?[0].locality)
}
回答你自己的问题很好,但请不要只是张贴代码。解释原始代码有什么问题,解释这个答案是如何解决问题的。结果证明我错了,我仍然没有得到邮政编码输入的自治区。请看我修改过的问题。相反,我得到了这个城市。。