问题描述
我正在开展一个项目,在该项目中我使用 CLGeocoder 来确定特定位置的地标。 像这样的非常简单的调用。
CLGeocoder().geocodeAddressstring(location) { (placemarks,error) in
if let error = error {
print(error.localizedDescription)
}
我希望能够捕获 CLError 代码并做出相应的响应,而不是打印出 NSError 的 localizedDescription。例如,如果找不到位置,我的 localizedDescription 打印
The operation Couldn’t be completed. (kCLErrorDomain error 8.)
我怎样才能在 Swift 中确定 CLError 代码,这样我就不必打开一些会根据用户的语言环境而改变的本地化描述? 这能做到吗? 我只有几个案例要开启。
解决方法
您需要将错误转换为 CLError
,然后切换错误 code
:
if let error = error as? CLError {
switch error.code {
case .locationUnknown:
print("locationUnknown: location manager was unable to obtain a location value right now.")
case .denied:
print("denied: user denied access to the location service.")
case .promptDeclined:
print("promptDeclined: user didn’t grant the requested temporary authorization.")
case .network:
print("network: network was unavailable or a network error occurred.")
case .headingFailure:
print("headingFailure: heading could not be determined.")
case .rangingUnavailable:
print("rangingUnavailable: ranging is disabled.")
case .rangingFailure:
print("rangingFailure: a general ranging error occurred.")
default : break
}
}