After my app has been backgrounded for a while and I foreground the app CLLocationManager
will fire and I will get a CLError.denied
error even after the app has .authorizedWhenInUse
permission.
init() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
locationManager.startUpdatingLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
guard let clErr = error as? CLError else {
return
}
switch clErr.code {
case CLError.denied:
showDeniedLocationError()
break
default:
break
}
}
For example in the above didFailWithError
the CLError.denied
case will get hit if the app was backgrounded for a reasonable amount of time EVEN THOUGH it definitely has permission to get your location. This problem only seems to happen when the app was backgrounded for a while and you foreground the app to continue using it. The app will immediately hit CLError.denied
and the error will be shown.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = manager.location {
locationManager.stopUpdatingLocation()
// update the location
}
}
Should I even be calling locationManager.stopUpdatingLocation()
in didUpdateLocations
?
When the app is foregrounded do I need to call locationManager.startUpdatingLocation()
every time to try and get around this problem?