如何在swift中使用CoreLocation从英国邮政编码获得自治市镇?

时间:2018-03-11 15:34:52

标签: swift core-location

有没有人知道我是否可以使用CoreLocation框架从英国邮政编码获得自治市镇?在下面列出的功能中,不返回行政区。它应该归还Tower Hamlets。

  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..

1 个答案:

答案 0 :(得分:0)

为了从邮政编码中获取位置,您只需要下标placemarks数组,然后在所需的indexPath处访问元素的属性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)

    }