-2

Hey does anyone know how to make a button that fills a UITextField with the users current address? I'm open to any frameworks or API's I just need push in the right direction, maybe a tutorial. Thanks.

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
VelveDeer
  • 1
  • 3
  • 1
    Already answered here: https://stackoverflow.com/questions/25296691/get-users-current-location-coordinates – Martheli Sep 09 '17 at 05:07

1 Answers1

0

Updated Solution:

To get the users location in longitude and latitude first you will have to

  1. Add import CoreLocation to your class
  2. Add CLLocationManagerDelegate to your class declaration
  3. Add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription to your info.plist file. You simply do this by pressing the add button and just copy and pasting one either one of them into it. It should auto correct to Privacy - Location When In Use Usage Description and then you can add a description in the box to the right of it. That description will appear in the pop up when the app asks to use the user's location.
  4. You then need to initiate location manager. You can do this by using

    let manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()
    
  5. You can then get the user's location using

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locat = manager.location
    

    }

Now that you have the user's location in longitude and latitude, you'll have to use geocoding to convert it into an address. To do this you have to

  1. Add import AddressBookUI to your class
  2. Create a CLGeocoder such as let geocoder: CLGeocoder = CLGeocoder()
  3. Implement a reverse geocoding function

    geocoder.reverseGeocodeLocation(locat!, completionHandler: {
        (placemarks, error) in
        if (error != nil) {
            //geocoding failed
        } else {
            let pm = placemarks! as [CLPlacemark]
    
            if pm.count > 0 {
                let pm = placemarks![0]
                let address = (pm.subThoroughfare + ", " + pm.thoroughfare + ", " + pm.locality + ", "  + pm.subLocality + ", " + pm.country + ", " + pm.postalCode)
                print(address)
                manager.stopUpdatingLocation()
            }
        }
    })
    

This function takes the users current location which we already figured out before and then takes each bit of the location, orders it correctly, and prints it into the console. It then stops updating the user's location.

Then finally, you can just change the text of the UIButton to that string containing the address.

Max Kortge
  • 527
  • 7
  • 23