F. Bar F. Bar - 15 days ago 5
Swift Question

How to handle when a user does not allow location

I'm currently playing around with location services on iPhone and have made a view controller with a single button.

I've created an action outlet to the button which when pressed I want to request for the users location.

@IBAction func requestLocation(_ sender: AnyObject) {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest

I've also called my checkLocation() function which checks the authorisation status of this, but It's being called before the user gets chance to allow or disallow the request.

func checkLocation() {
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
} else {
print("Location services are not enabled")

Is there a way I can handle when the user presses both allow and disallow.


When you added NSRequestWhenInUse in your info.plist file, System alert will show on first time when app will open. In that alert there are two option 'Allow' and 'Cancel'. So when user clicks allow it will go to settings and when user enable location, your app will update location of user. So you do not have to do anything menually.

enter image description here

And add this method,

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error?) {
    // [manager stopUpdatingLocation];
    switch error!.code {
        case kCLErrorNetwork:
        // general, network-related error
                        var alert = UIAlertView(title: "Location Error!", message: "Can't access your current location! Please check your network connection or that you are not in airplane mode!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")

        case kCLErrorDenied:
                        var alert = UIAlertView(title: "Location Error!", message: "Location Access has been denied for app name!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")
            // alert.tag=500;

                        var alert = UIAlertView(title: "Location Error!", message: "Can't access your current location!", delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: "")