Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire 2, how to get NSError?

In alamofire 2 they introduced result types:

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")
        case .Failure(let data, let error):
            print(error)
        }
    }

error is of type ErrorType and its only member is debugDescription which prints:

Optional(Error Domain=NSURLErrorDomain Code=-1009 "Es besteht anscheinend keine Verbindung zum Internet." UserInfo={NSUnderlyingError=0x135f4e7c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=8, _kCFStreamErrorDomainKey=12}}, NSErrorFailingURLStringKey=myurl, NSErrorFailingURLKey=myurl, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=Es besteht anscheinend keine Verbindung zum Internet.})

How can I get just the NSLocalizedDescription from the error and not the whole debug message?

In alamofire 1 the error was of type NSError and could get the error message with:

error.localizedDescription

however this seems to be not possible in alamofire 2. Any ideas?

like image 262
UpCat Avatar asked Jan 07 '23 13:01

UpCat


2 Answers

In the "Alamofire 2.0 Migration Guide" it is stated that a new result type

public enum Result<Value> {
    case Success(Value)
    case Failure(NSData?, ErrorType)
}

was introduced and that Alamofire still only generates NSError objects.

In "Why and how any ErrorType can always be casted to NSError?" a member of the Apple Stuff confirmed that an ErrorType can always be cast to an NSError:

... The reason this works is because of "compiler magic." The compiler automatically emits the code necessary to translate between any ErrorType and NSError.

So this compiles and printed the expected result in a quick test (e.g. "Could not connect to the server."):

switch result {
case .Success(let JSON):
    print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
    print((error as NSError).localizedDescription)
}
like image 144
Martin R Avatar answered Jan 15 '23 10:01

Martin R


The ErrorType can be converted to an NSError. Try this:

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")
        case .Failure(let data, let error):
            if let error = error as NSError? {
                print(error.localizedDescription)
            }
        }
    }
like image 45
Bannings Avatar answered Jan 15 '23 12:01

Bannings