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

时间:2016-12-01 08:02:00

标签: ios swift uitextfield state city

我有五个textFields,我想在输入密码时自动填写区域,城市,州和国家。

 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)
  }
}

我该怎么做? 感谢

1 个答案:

答案 0 :(得分:5)

您可以使用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)