Swift 4的更新:错误现在被传递给回调,因为error: Error
它可以转换为CLError
:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if let clErr = error as? CLError {
switch clErr {
case CLError.locationUnknown:
print("location unknown")
case CLError.denied:
print("denied")
default:
print("other Core Location error")
}
} else {
print("other error:", error.localizedDescription)
}
}
较旧的答案:核心位置错误代码定义为
enum CLError : Int {
case LocationUnknown // location is currently unknown, but CL will keep trying
case Denied // Access to location or ranging has been denied by the user
// ...
}
并将枚举值与整数进行比较err.code
,toRaw()
可以使用:
if err.code == CLError.LocationUnknown.toRaw() { ...
或者,您可以从错误代码创建一个CLError
并检查可能的值:
if let clErr = CLError.fromRaw(err.code) {
switch clErr {
case .LocationUnknown:
println("location unknown")
case .Denied:
println("denied")
default:
println("unknown Core Location error")
}
} else {
println("other error")
}
更新:在 Xcode 6.1 beta 2 中,fromRaw()
和toRaw()
方法已分别被init?(rawValue:)
初始化器和rawValue
属性替换:
if err.code == CLError.LocationUnknown.rawValue { ... }
if let clErr = CLError(rawValue: code) { ... }