Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire 3.2: How do I validate the response of an 'upload' POST call?

I have a simple upload POST call,

Alamofire.upload(
    .POST,
    "https://httpbin.org/post",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
    },
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    }
)

It always goes to .Success case even when the response is a 404/500 error.

My question is, how do I validate this request's response?

like image 667
Nagendra Rao Avatar asked Feb 16 '16 06:02

Nagendra Rao


1 Answers

Validation

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. Manual Validation

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
     .validate(statusCode: 200..<300)
     .validate(contentType: ["application/json"])
     .response { response in
         print(response)
     }

Automatic Validation

Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
     .validate()
     .responseJSON { response in
         switch response.result {
         case .Success:
             print("Validation Successful")
         case .Failure(let error):
             print(error)
         }
     }

well, at last

case .Success(let upload, _, _):
                upload.validate(statusCode: 200..<300)
                    .validate(contentType: ["application/json"])
                    .response { response in
                        print(response)
                }
like image 149
Ethan Avatar answered Nov 16 '22 14:11

Ethan