Swift 斯威夫特从Zipcode获得城市

Swift 斯威夫特从Zipcode获得城市,swift,cncontact,Swift,Cncontact,我有一张用户填写的登记表。我希望他们只需要输入他们的zipcode,让我的程序能够推断他们的城市和州,这样他们就不必手动编写这些代码了,界面更干净,输入字段更少 我该怎么做?您必须在应用程序中添加一个参考,将城市与邮政编码(硬编码或plist文件或核心数据)关联起来。然后,在用户输入邮政编码时检索并显示信息。您可以使用CoreLocation框架进行此操作。将zipcode作为字符串,让框架进行最佳猜测,或者向用户展示猜测,让他们选择一个: import UIKit import CoreLoc

我有一张用户填写的登记表。我希望他们只需要输入他们的zipcode,让我的程序能够推断他们的城市和州,这样他们就不必手动编写这些代码了,界面更干净,输入字段更少


我该怎么做?

您必须在应用程序中添加一个参考,将城市与邮政编码(硬编码或plist文件或核心数据)关联起来。然后,在用户输入邮政编码时检索并显示信息。

您可以使用CoreLocation框架进行此操作。将zipcode作为字符串,让框架进行最佳猜测,或者向用户展示猜测,让他们选择一个:

import UIKit
import CoreLocation

let zipCode = "1234AB"

let geocoder = CLGeocoder()
geocoder.geocodeAddressString(zipCode) {
    (placemarks, error) -> Void in
    // Placemarks is an optional array of CLPlacemarks, first item in array is best guess of Address

    if let placemark = placemarks?[0] {

        print(placemark.addressDictionary)
    }

}

请参见和

对于任何试图获得城市的人:placemark.locality!州:placemark.administrativeArea!无法完成该操作。(kCLErrorDomain错误8)-Swift 3.0这似乎有点不切实际,考虑到互联网上搜索的USI中有多少Zipcode和城市,似乎只有“大约”43.000/44.000个邮政编码。CoreData或SQLite库可以轻松存储这些元素
**Not working. its not printing anything**

import UIKit
import CoreLocation

let zipCode = "1234AB"

let geocoder = CLGeocoder()
geocoder.geocodeAddressString(zipCode) {
    (placemarks, error) -> Void in
    // Placemarks is an optional array of CLPlacemarks, first item in array is best guess of Address

    if let placemark = placemarks?[0] {

        print(placemark.addressDictionary)
    }

}