In an iOS app, when the user denies location permission, I want to show an alert to give permission. I debug it and code works successfully but I can’t see any alert in the simulator.
I start the program and deny location permission. I then restart it and I can’t show any alert.
func checkLocationAuthorizationStatus() {
let status = locationManager.authorizationStatus
switch status{
case .authorizedWhenInUse, .authorizedAlways: //eğer iki izinden biri alınmış ise burası çalışıcak
locationManager.startUpdatingLocation()
case .denied, .restricted: //red yemiş ise burası çalışıcak
showLocationAccessAlert()
case .notDetermined: //henüz konum izni vermemiş
locationManager.requestWhenInUseAuthorization()
@unknown default:
break
}
}
func showLocationAccessAlert() {
let alert = UIAlertController(
title: "Konum Erişimi Gerekli",
message: "Lütfen Ayarlar'dan konum iznini etkinleştirin.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Ayarlar", style: .default) { _ in
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
}
})
alert.addAction(UIAlertAction(title: "Vazgeç", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
2
Answers
The iOS simulator sometimes has issues with location permissions. Testing on a physical device.
If the problem continues, please ensure the alert code is executed on the main thread.
Solution
Use CLLocationManager.authorizationStatus (or locationManager.authorizationStatus in iOS 14+) to determine the current location permission status.
Display an Alert: If the permission status is .denied or .restricted, show an alert that explains why location access is needed, with an option to open the app’s settings.
Open App Settings: In the alert, add a button that opens the app’s settings where users can manually enable location permissions.
Additional Tips
Test on a Real Device: Simulators sometimes behave inconsistently with location permissions, so testing on an actual device is recommended.