Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show alert when Location is disabled by the user in Swift?

My Swift app asks to allow access to current location via CLLocationManager. How can I display an alert message when the user taps on "Don't Allow"?

like image 807
Esthon Wood Avatar asked Aug 14 '15 02:08

Esthon Wood


People also ask

How do I show location pop up in Swift?

There isn't any default functionality which will popup the location permission once the user has denied the permission. You need to show an alert to the user that permission is required, and then redirect the user to Settings screen.

How do you check location permission is enable or not in Swift?

Basic Swift Code for iOS Apps You should check the return value of locationServiceEnabled() method before starting location updates to determine whether the user has location services enabled for the current device.

How do I trigger alerts in Swift?

To show an alert, create some Boolean state that determines whether the alert should be visible, then attach that to an alert() modifier along with all the buttons you want to show in the alert. All buttons dismiss the alert when tapped, so you can provide an empty action for simple dismissal.

How do I turn on location services in Swift?

Open your phone's Settings app. Under "Personal," tap Location access. At the top of the screen, turn Access to my location on or off.


1 Answers

You want to look at

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) 

and

CLLocationManager.authorizationStatus()

The first is invoked when the user changes authorization status and the second will allow you to determine current status at any time.

Then, displaying the message, for example:

let alert = UIAlertController(title: "Your title", message: "GPS access is restricted. In order to use tracking, please enable GPS in the Settigs app under Privacy, Location Services.", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Go to Settings now", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) in
                print("")
                UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
            }))

the code above shows an alert and allows the user to go directly to settings to enable location.

like image 81
MirekE Avatar answered Nov 01 '22 15:11

MirekE