Sotiris Kaniras Sotiris Kaniras - 4 months ago 47
Swift Question

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?

Adi Adi

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

let locationManager = CLLocationManager()

In viewDidLoad():

  // Ask for Authorisation from the User.

  // For use in foreground

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

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)")
    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
        case .Default: UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
        case .Cancel: print("cancel")
        case .Destructive: print("destructive")