Swift Alamofire: How to Get the Http Response Status Code

Alamofire + Combine: Get the HTTP response status code

If you want the response code, don't erase the DataPublisher using .value(). Instead, use the DataResponse you get from the various publish methods, which includes all of the various response information, including status code. You can then .map it into whatever type you need.

Alamofire returns .Success on error HTTP status codes

From the Alamofire manual:

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.

You can manually validate the status code using the validate method, again, from the manual:

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

Or you can semi-automatically validate the status code and content-type using the validate with no arguments:

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)
}
}

Get HTTP Status-Line in Alamofire

Unfortunately no

Alamofire uses the URLResponse and it does not implement any field/method that gives you information about Status-Line. To get the Status-Line you should use other maybe lower-level frameworks.

URLResponse gives you only information about allHeaderFields, you can look on my answer about it here :

https://stackoverflow.com/a/36524454/5433235

How to detect 304 statusCode with Alamofire

Since NSURLSessions default behavior is to abstract from cached 304 responses by always returning 200 responses (but not actually reloading the data), I first had to change the cachingPolicy as follows:

urlRequest.cachePolicy = .reloadIgnoringCacheData

Then, I adjusted the status codes of the validate function to accept 3xx responses and handled the codes accordingly:

Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<400)
.responseData { response in
switch response.response?.statusCode {
case 304?:
print("304 Not Modified")
default:
switch response.result {
case .success:
print("200 Success")
case .failure:
print ("Error")
}
}
}


Related Topics



Leave a reply



Submit