Sotiris Kaniras Sotiris Kaniras - 9 days ago 6
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
Answer

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")
        }
    }))
}
Comments