Ios 如何检查地理定位是否打开?
我有一个Ios 如何检查地理定位是否打开?,ios,swift,core-location,Ios,Swift,Core Location,我有一个按钮,可以获取我的当前位置,但当我在关闭地理位置的情况下单击它时,应用程序崩溃 我想写一个案例,如果用户关闭了他的地理数据,我建议用户通过特殊的警报窗口打开它 是否有任何corelocation方法解决此问题?当您调用-startLocation时,如果用户拒绝了定位服务,则location manager代表将收到一个调用-locationManager:didFailWithError:的错误代码 locationManager:didChangeAuthorizationStatu
按钮
,可以获取我的当前位置,但当我在关闭地理位置的情况下单击它时,应用程序崩溃
我想写一个案例,如果用户关闭了他的地理数据,我建议用户通过特殊的警报窗口打开它
是否有任何
corelocation
方法解决此问题?当您调用-startLocation
时,如果用户拒绝了定位服务,则location manager代表将收到一个调用-locationManager:didFailWithError:
的错误代码 locationManager:didChangeAuthorizationStatus在CLLocationManager初始化后不久被调用
因此,添加此函数以获取位置状态:
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
print("Restricted")
case CLAuthorizationStatus.Denied:
print("Denied")
default:
break
}
}
Swift 4语法:
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")
}
}
在尝试获取位置之前处理位置状态:
// 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
}
}