简体   繁体   中英

How to ask permission (RunTime) again if the user deny for the first time swift

I deny location permission first app launch and when user click the location Button i want to display alert dialog asking for permission.

Here is my sudo code

Click location Button

if dont have location permission {
   ask for permission
} else {
  get current location
}

Here is my code.please check the comments in my code.Hope you understand my problem.Thanks in advance.

@IBAction func getCurrentLocationButtonClick(_ sender: UIButton) {
///////////How to implement that sudo code/////////////////////////////
///////////Why This method is not calling for second time /////////////
//        locationManager.desiredAccuracy = kCLLocationAccuracyBest
//        locationManager.requestWhenInUseAuthorization()
//        locationManager.requestLocation()
/////////////////////////////////////////////////////
          locationManager.startUpdatingLocation()   
   }


override func viewWillAppear(_ animated: Bool) {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()
}

extension NotificationCenterViewController : CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        /*

        if status == .denied {
            let alertController = UIAlertController(title: "Error", message: "We need your location.plese give permission", preferredStyle: .alert)

            let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in
                //Ask for location permission
            }

            alertController.addAction(OKAction)
            self.present(alertController, animated: true)
        }

         */

        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
            // locationManager.startLocationUpdates()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation: CLLocation = locations[0]
        locationManager.stopUpdatingLocation()
        let latitude = userLocation.coordinate.latitude
        let longitude = userLocation.coordinate.longitude
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        print("error:: (error)")
    }
}

When you discover that location is denied, you only can open app settings here is example of alert with that

let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)

You request permission by calling requestWhenInUseAuthorization() on your location manager. The problem with your pseudo-code is that you shouldn't do that every time but only once, after that the user should go to Settings to change the permission. CLLocationManager holds a permission status that can be checked for this. You can do something like this in your IBAction

let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
    locationManager.requestWhenInUseAuthorization()
    return
}

if status == .denied || status == .restricted {
    //Display alert that user needs to enable permissions in Settings 
    // or open settings directly as in the other answer
    showAlert()
    return
}

//Code to get location here....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM