swiftxcodeerror-handlingclgeocoder

CLGeocoder().geocodeAddressString error codes


I am working on a project where I use CLGeocoder to determine the placemarks for a particular location. Very simple call like this.

CLGeocoder().geocodeAddressString(location) { (placemarks, error) in
            if let error = error {
                print(error.localizedDescription)
            }

Instead of printing out the NSError's localizedDescription, I would like to be able to capture the CLError code and respond accordingly. For example, if the location can't be found, my localizedDescription prints

The operation couldn’t be completed. (kCLErrorDomain error 8.)

How can I, in Swift determine the CLError code so that I do not have to switch on some localized description that will change based on user's locale? Can this be done? I only have a couple of cases that I want to switch on.


Solution

  • You need to cast the error as CLError and then switch the error 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
        }
    }