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.
Asked
Active
Viewed 644 times
-2
-
1Already answered here: https://stackoverflow.com/questions/25296691/get-users-current-location-coordinates – Martheli Sep 09 '17 at 05:07
1 Answers
0
Updated Solution:
To get the users location in longitude and latitude first you will have to
- Add
import CoreLocation
to your class - Add
CLLocationManagerDelegate
to your class declaration - Add
NSLocationWhenInUseUsageDescription
orNSLocationAlwaysUsageDescription
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 toPrivacy - 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. 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()
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
- Add
import AddressBookUI
to your class - Create a
CLGeocoder
such aslet geocoder: CLGeocoder = CLGeocoder()
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