I am uploading a file to a server which responds, occasionally, with an error 500. The problem is that the result is marked as a success and this confuses my client code something fierce. Here's an example of the problem:
let endpointUrl = NSURL("http://aserver.com/somepath/uploadImageEndpoint")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: endpointUrl!, cachePolicy: cachePolicy, timeoutInterval: 60.0)
request.HTTPMethod = "POST"
// set credentials
let userCredentials = UserCredentials()
let base64EncodedCredentials = userCredentials.base64EncodedCredentials()
request.setValue("Basic \(base64EncodedCredentials)", forHTTPHeaderField: "Authorization")
// set boundary
let boundary = "NET-POST-boundary-\(arc4random())-\(arc4random())"
request.setValue("multipart/form-data;boundary="+boundary,
forHTTPHeaderField: "Content-Type")
// create request parameters
let parameters = NSMutableData()
for s in ["\r\n--\(boundary)\r\n",
"Content-Disposition: form-data; filename=\"userimage.png\"\r\n",
"Content-Type: image/png\r\n\r\n"] {
parameters.appendData(s.dataUsingEncoding(NSUTF8StringEncoding)!)
}
parameters.appendData(UIImagePNGRepresentation(image)!)
parameters.appendData("\r\n--\(boundary)--\r\n"
.dataUsingEncoding(NSUTF8StringEncoding)!)
upload(request, data: parameters).responseData() { (_, response, result) in
if(response?.statusCode == 500) {
NSLog("@@@@@@@@@@@@@@@ Received 500")
}
if(result.isSuccess) {
NSLog("@@@@@@@@@@@@@@@ result is success")
}
if(result.isFailure) {
NSLog("@@@@@@@@@@@@@@@ result is failure")
}
switch result {
case .Success(_):
successHandler()
case .Failure(_, let error):
let nsError = error as NSError
errorHandler(nsError)
}
}
This will output:
@@@@@@@@@@@@@@@ Received 500
@@@@@@@@@@@@@@@ result is success
I don't believe this an intuitive result. The result should be a failure if the server returns a 500.
This issue was encountered in XCode 7.0.1 running an iPhone 6 simulator which is simulating iOS 9.0.1
By default Alamofire registers any response that makes it through the response serializer (in your example, the dataResponseSerializer used by .responseData) as a success. If you wish to validate the response code of your request, just add a .validate() to your request chain. This will ensure that your response code is between 200 and 299, inclusive. You can also customize validation using the methods described in the documentation.
Thank you Jon, great response!
Most helpful comment
By default Alamofire registers any response that makes it through the response serializer (in your example, the
dataResponseSerializerused by.responseData) as a success. If you wish to validate the response code of your request, just add a.validate()to your request chain. This will ensure that your response code is between 200 and 299, inclusive. You can also customize validation using the methods described in the documentation.