如何在 Swift iOS 中通过 Pincode 获取城市、州和国家名称?

How to get city , state and Country name by Pincode in Swift iOS?

我有五个文本字段,我想在输入密码时自动填充区域、城市、州和国家/地区。

 import UIKit
 import CoreLocation

class CreateGroupView: UIViewController,UITextFieldDelegate,CLLocationManagerDelegate
{
   //View Did Load
  override func viewDidLoad() {
      super.viewDidLoad()

    let location: String = "305621"//"yourPINCode"
    let geocoder: CLGeocoder = CLGeocoder()
    geocoder.geocodeAddressString(location,completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
        if ((placemarks?.count)! > 0) {
            let placemark: CLPlacemark = (placemarks?[0])!
            let country : String = placemark.country!
            let state: String = placemark.administrativeArea!
            print(country)
            print(state)
        }
    } as! CLGeocodeCompletionHandler)
  }
}

我该怎么做? 谢谢

您可以使用 CLGeocoder 从 PIN 码中获取地址的详细信息,这里是示例代码。

   let location: String = "yourpincode"
let geocoder: CLGeocoder = CLGeocoder()
geocoder.geocodeAddressString(location, completionHandler: {(placemarks: [CLPlacemark]?, error: Error?) -> Void in
    if ((placemarks?.count)! > 0) {
        let placemark: CLPlacemark = (placemarks?[0])!
        let country : String = placemark.country!
        let state: String = placemark.administrativeArea!
        print(state);
    }
} as! CLGeocodeCompletionHandler)