Reputation: 2268
I have a button
, that can get my current location, but when I click on it with switched off geolocation the app app crashes.
I want to write a case, if the user has switched off his geodata, I suggest the user to switch it on through special alert window.
Are there any corelocation
methods for such issue?
Upvotes: 0
Views: 195
Reputation: 38833
locationManager:didChangeAuthorizationStatus
is called shortly after the CLLocationManager is initialized.
So add this function to get the location status:
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
print("Restricted")
case CLAuthorizationStatus.Denied:
print("Denied")
default:
break
}
}
Swift 4 syntax:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("restricted")
case .denied:
print("denied")
case .notDetermined:
print("notDetermined")
case .authorizedAlways:
print("authorizedAlways")
case .authorizedWhenInUse:
print("authorizedWhenInUse")
}
}
Apples reference to CLAuthorizationStatus.
Upvotes: 2
Reputation: 10294
Handle the location status before trying to fetch the location:
// create enum to check
enum Usage {
case WhenInUse
case Always
}
func checkLocationAuthorization(usage: Usage) {
let enabled = CLLocationManager.locationServicesEnabled()
let actual = CLLocationManager.authorizationStatus()
var error: NSError?
// There are several factors to consider when evaluating this condition
switch (enabled, usage, actual) {
case (true, _, .AuthorizedAlways):
// The service is enabled, and we have "Always" permission -> condition satisfied.
break
case (true, .WhenInUse, .AuthorizedWhenInUse):
/*
The service is enabled, and we have and need "WhenInUse"
permission -> condition satisfied.
*/
break
default:
/*
Anything else is an error. Maybe location services are disabled,
or maybe we need "Always" permission but only have "WhenInUse",
or maybe access has been restricted or denied,
or maybe access hasn't been request yet.
The last case would happen if this condition were wrapped in a `SilentCondition`.
*/
error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.locationServicesEnabledKey: enabled,
self.dynamicType.authorizationStatusKey: Int(actual.rawValue)
])
}
if let error = error {
// Handle not enabled condition here
}
else {
// Location is enabled and continue the user actions
}
}
Upvotes: 0
Reputation: 712
When you call -startLocation
, if location services were denied by the user, the location manager delegate will receive a call to - locationManager:didFailWithError:
with the kCLErrorDenied
error code.
Upvotes: 0