CLGeocoder().geocodeAddressString 错误代码

CLGeocoder().geocodeAddressString error codes

我正在做一个项目,我使用 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
    }
}