Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Core location request permission if not granted

Is there any way to ask users to give permission for location detection, if they denied when they were first asked?

like image 353
Sotiris Kaniras Avatar asked Dec 06 '22 16:12

Sotiris Kaniras


2 Answers

For getting user's current location you need to declare:

let locationManager = CLLocationManager()

In viewDidLoad():

  // Ask for Authorisation from the User.
  self.locationManager.requestAlwaysAuthorization() 

  // For use in foreground
  self.locationManager.requestWhenInUseAuthorization()

  if CLLocationManager.locationServicesEnabled() {
      locationManager.delegate = self
      locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
      locationManager.startUpdatingLocation()
  }

Then in CLLocationManagerDelegate method you can get user's current location coordinates:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var locValue:CLLocationCoordinate2D = manager.location.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

If user has denied the location then give him option to change location permission from settings:

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("error::: \(error)")
    locationManager.stopUpdatingLocation()
    let alert = UIAlertController(title: "Settings", message: "Allow location from settings", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alert, animated: true, completion: nil)
    alert.addAction(UIAlertAction(title: TextMessages().callAlertTitle, style: .Default, handler: { action in
        switch action.style{
        case .Default: UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
        case .Cancel: print("cancel")
        case .Destructive: print("destructive")
        }
    }))
}

NOTE:

Make sure to add the Privacy key (NSLocationAlwaysAndWhenInUseUsageDescription) to Info.plist file.

like image 140
Aditya Avatar answered Jan 01 '23 09:01

Aditya


No, you can just remind them inside app within an alert, like "For better usage, we will suggest you to give us the permissions to use your location". And to add button "Go to settings" that will redirect the user to the Location Permissions for your application.

like image 36
Lexorus Avatar answered Jan 01 '23 07:01

Lexorus