Search code examples
swiftcncontact

Swift Get City from Zipcode


I have a registration form the user fills out. I'd like them to only have to enter their zipcode and have my program be able to infer their city and state so they don't have to write those manually / to have a cleaner interface with fewer entry fields.

How would I do this?


Solution

  • You can use the CoreLocation framework for this. Take the zipcode as a string and have the framework take its best guess or present the user with the guesses and have them select one:

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

    See CLGeoCoder and CLPlaceMark