Swift – Get Users Location GPS Coordinates
Most Mapping libraries such as Google Maps and Apple Maps show you where the user currently is and also allows you to get their coordinates. But what if you want to get the user’s location without using one of these libraries. You might want to save their location to a database, show app options based on the location and so on.
In this tutorial you will learn how to get the users coordinates (Longitude & Latitude), and also how to handle the case where they reject your app’s access to this information with deep linking.
Getting access to the users location & Deep Linking
First of all create a new single view application. We need to setup the permissions first, otherwise we can’t get access to the users location at all. To do this first of all select, your project then select targets. Go to the info tab, under Custom iOS Target Properties hover over one of the items and select the “+”.
You need to add the following two properties
- Privacy – Location Always Usage Description
- Privacy – Location When In Use Usage Description
The value is the message shown to the user when requesting access to their location. To be sure to keep it short and concise, but convey to them why your app needs access to their location otherwise they might reject it. Also the differences between the two are:
- Location Always Usage Description – This pops up when we request access to the location even when the App is closed
- Location When In Use Usage Description – This pops up when we request access to the location only when the App is open
Then make your ViewController code as follows. The code is commented explaining what each section does with some important notes below:
import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { // Used to start getting the users location let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // For use when the app is open & in the background locationManager.requestAlwaysAuthorization() // For use when the app is open //locationManager.requestWhenInUseAuthorization() // If location services is enabled get the users location if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest // You can change the locaiton accuary here. locationManager.startUpdatingLocation() } } // Print out the location to the console func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { print(location.coordinate) } } // If we have been deined access give the user the option to change it func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if(status == CLAuthorizationStatus.denied) { showLocationDisabledPopUp() } } // Show the popup to the user if we have been deined access func showLocationDisabledPopUp() { let alertController = UIAlertController(title: "Background Location Access Disabled", message: "In order to deliver pizza we need your location", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) let openAction = UIAlertAction(title: "Open Settings", style: .default) { (action) in if let url = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } alertController.addAction(openAction) self.present(alertController, animated: true, completion: nil) } }
- Import CoreLocation at the top to get access to the library needed for location functionality
- Add CLLocationManagerDelegate to the viewController, we need this as the didUpdateLocations function is called once we have the user location.
- viewDidLoad kicks off getting the users location
- showLocationDisabledPopUp will be called if the user has denied our app access to the location. One of the options it presents to the user is Open Settings. It uses deep linking to open up the settings for this app directly. You want to do this as if you were to give the user instructions on how to get to the settings, they would most likely never change it.