1

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?

36 By Design
  • 3,203
  • 3
  • 18
  • 18

3 Answers3

9

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

Emptyless
  • 2,964
  • 3
  • 20
  • 30
-3

You have to add a reference in your app that associate the city with the zip code (hard-coded or in a plist file or core-data). Then retrieve and display the information when the user enters the zip code.

FredericP
  • 1,119
  • 1
  • 14
  • 27
  • 1
    This seems a little impractical given how many zipcodes and cities there are just in the US – 36 By Design Apr 10 '16 at 16:00
  • I searched on Internet, it seems there's 'just' about 43.000/44.000 ZIP codes. A CoreData or SQLite base could store these elements easily – FredericP Apr 10 '16 at 16:34
-3
**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)
    }

}