How to request permission programatically to use location services in iPhone/iOS?

iOSiPhone/iPadMobile Development

To request location services permission in ios with swift we can use the CLLocationManager.

We’ll do this with help of a sample project. So, create a new project. First, we need to create a locationManager object, so in your view controller.

var locationManager = CLLocationManager()

Now, we, first of all, we need to check if the location services are enabled on the device or not. To check this we’ll use

CLLocationManager.locationServicesEnabled() function, which returns a Boolean value showing whether the location service on the device is active or not.

if CLLocationManager.locationServicesEnabled() {
   print("permissions allowed")
} else {
   locationManager.requestAlwaysAuthorization()
   locationManager.requestWhenInUseAuthorization()
}

In the example above, if the location services are enabled, then we print “permissions allowed”, otherwise we request two kind of authorizations, alwaysInUse, and WhenInUse authorization.

Now, let’s see another example where we’ll see what kind of permission is granted if the location services are active on a device.

We’ll use the CLLocationManager.authorizationStatus() method, which returns us the kind of authorization given. It is an enum which has 5 possible values.

As per the official Apple documentation, the enum has the following values.

notDetermined, restricted, denied, authorized, authorizedWhenInUse.

Let’s see the other example.

if CLLocationManager.locationServicesEnabled() {
   switch CLLocationManager.authorizationStatus() {
      case .authorizedAlways,.authorizedWhenInUse : print("authorized.")
      case .denied,.restricted,.notDetermined : print("not authorized.")
   }
}
raja
Published on 30-Jan-2019 09:45:11
Advertisements