Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlamofireObjectMapper responseObject method migrating issue

I have a problem with the AlamofireObjectMapper responseObject method. It's completionHandler changed from Response<T, NSError> -> Void (old) to DataResponse<T> -> Void (now). Maybe I don't get it but can you please tell me how can I provide backend error handling now with this change? Before, I had in completion for example Response<Object, NSError>. Now I can't handle both the backend error and the on success received data. Or should I use other approach?

For example now I have: Xcode 8 , swift 3, updated frameworks

class func getAllProducts(successCallBack:((ProductsData?) -> Void), failureCallBack: ((NSError?, ServerResponseStatusCode?) -> Void)?) {

        Alamofire.request(URLRouter.Products).responseObject {
            (response: DataResponse<ProductsData, NSError>) in

            // inside completion block code
        }
    }

But as I checked in the new updated AlamofireObjectMapper, this method's completion now is of form DataResponse<T> only, and because of this I get the error "Generic type "DataResponse" specialized with too many type parameters(got 2 but expected 1)"

Before: working Xcode 7, swift 2.2

class func getAllProducts(successCallBack:((ProductsData?) -> Void), failureCallBack: ((NSError?, ServerResponseStatusCode?) -> Void)?) {

        Alamofire.request(URLRouter.Products).responseObject {
            (response: Response<ProductsData, NSError>) in

            // inside completion block code
        }
    }

Thank you very much.

like image 798
Toparceanu Rares Avatar asked May 22 '26 13:05

Toparceanu Rares


1 Answers

In Alamofire 4.0 using Swift 3.0, you may need to reach error/failures within switch statement inside the response closure:

Alamofire.request(URLRouter.Products, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.validate()    
.responseObject { response in
    switch response.result {
        case .success:
            //print("...HTTP code: \ (response.response?.statusCode)")

        case .failure(let error as NSError):
            print("Error: \(error)")

        default:
            print("Unexpected case")
    }
}
like image 137
pedrouan Avatar answered May 25 '26 10:05

pedrouan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!