Is there any way to ask users to give permission for location detection, if they denied when they were first asked?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With