Reputation: 153
How can I use Core Location's locationManagerDidChangeAuthorization(_:) method to check authorization status and report user location at the press of a button (called in @IBAction) below:
My issue here is that when I run the code in the simulator, CoreLocation doesn't pop up with an alert to ask the user for permission when the button is pressed.
class CurrentLocationViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
// Button to check authorization status and start sending location update to the delegate
@IBAction func getLocation() {
locationManagerDidChangeAuthorization(locationManager)
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
// Delegate method to check authorization status and request "When In Use" authorization
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let authStatus = manager.authorizationStatus
if authStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
}
EDIT: Using the deprecated authorizationStatus() class method in the @IBAction method instead of the locationManagerDidChangeAuthorization(_:) method allows me to get the pop up when the button is pressed in the simulator. I'm still trying to figure out why this modification works whereas my code above doesn't.
@IBAction func getLocation() {
let authStatus = CLLocationManager.authorizationStatus()
if authStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
...
Upvotes: 0
Views: 3989
Reputation: 143
You're code works - but have you remembered to add the privacy usage descriptions to the info.plist file?
Add these two entries in the file with your own explanation in the value field, then it should popup in the simulator:
Upvotes: 1