I have an application with an explicit user interaction that makes use of the user\'s current location. If the user denies access to location services, I would still like su
Swift,
Once you disable location services for an app, location manager delegate methods will start showing error. So, on receiving error we can check if location services are enabled/disabled. And according to the result, we can ask the user to go to settings and turn on location services.
In your location manager delegate method for error, add location permission check
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
//check location permissions
self.checkLocationPermission()
}
}
Code for location permission checking
//check location services enabled or not
func checkLocationPermission() {
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
//open setting app when location services are disabled
openSettingApp(message:NSLocalizedString("please.enable.location.services.to.continue.using.the.app", comment: ""))
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
}
} else {
print("Location services are not enabled")
openSettingApp(message:NSLocalizedString("please.enable.location.services.to.continue.using.the.app", comment: ""))
}
}
Code to open settings app,
//open location settings for app
func openSettingApp(message: String) {
let alertController = UIAlertController (title: APP_NAME_TITLE, message:message , preferredStyle: .alert)
let settingsAction = UIAlertAction(title: NSLocalizedString("settings", comment: ""), style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}