How to request Location Permission at runtime on iOS

To request location Permission we will be using Apple’s CLLocationManager class. You use instances of this class to configure, start, and stop the Core Location services.

You can read more about CLLocationManager class here.

iOS apps can support one of two levels of location access.

  • While using the app − The app can access the device’s location when the app is in use. This is also known as “when-in-use authorization.”

  • Always − The app can access the device’s location either when app is in use or in the background.

Here we will be using when-in-use authorization: Request authorization to use location services only when your app is running.

Step 1 − Open Xcode, Single View Application, name it LocationServices.

Step 2 − Open the Main.storyboard and add one button and name it getLocation.

Step 3 − In ViewController.swift add the @IBAction of the button

@IBAction func btnGetLocation(_ sender: Any) {

Step 4 − Import Corelocation to use location classes. import CoreLocation

Step 5 − Open your info.plist (to enable the permissions for location updates while the app is running a special key is needed). Right-click and select Add Row. Enter the following Values.

Step 6 Open ViewController.swift and create object of CLLocationManager,

let locationManager = CLLocationManager()

Step 7 − In ViewController.swift add the following code in button action,

@IBAction func btnGetLocation(_ sender: Any) {
   let locStatus = CLLocationManager.authorizationStatus()
   switch locStatus {
      case .notDetermined:
      case .denied, .restricted:
         let alert = UIAlertController(title: "Location Services are disabled", message: "Please enable Location Services in your Settings", preferredStyle: .alert)
         let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
         present(alert, animated: true, completion: nil)
      case .authorizedAlways, .authorizedWhenInUse:

The authorizationStatus returns the current authorisation status to the locStatus. The when in use authorisation get location updates while the app is in the foreground. When location services is disabled, the user will be shown an alert with message Location Services are disabled.

Let’s run the application,

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started