user6845426
user6845426

Reputation:

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
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
    checkLocation()
}

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:
            print("Access")
        }
    } else {
        print("Location services are not enabled")
    }
}

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

Upvotes: 1

Views: 1835

Answers (1)

KAR
KAR

Reputation: 3361

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];
    print("error\(error)")
    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: "")
            alert.show()

        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;
            alert.show()

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

Upvotes: 4

Related Questions