CLGeocoder().geocodeAddressString 错误代码

问题描述

我正在开展一个项目,在该项目中我使用 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
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...