Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect 304 statusCode with Alamofire

Is there a way to detect 304 Not Modified response with Alamofire 4? I find that Alamofire response.statusCode is always 200 even if server responded with 304.

Network call setup:

Alamofire 
    .request("http://domain.com/api/path", method: .get)
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseJSON { response in 
        print(response.response?.statusCode)
}

Alamofire response header

<NSHTTPURLResponse: 0x61800003e1c0> { URL: http://domain.com/api/path } { status code: 200, headers {
    "Access-Control-Allow-Headers" = "content-type, authorization";
    "Access-Control-Allow-Methods" = "GET, PUT, POST, DELETE, HEAD, OPTIONS";
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "private, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Mon, 23 Jan 2017 23:35:00 GMT";
    Etag = "\"f641...cbb6\"";
    "Proxy-Connection" = "Keep-alive";
    Server = "nginx/1.10.1";
    "Transfer-Encoding" = Identity;
} }

Server response

HTTP/1.1 304 Not Modified
Server: nginx/1.10.1
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Cache-Control: private, must-revalidate
ETag: "f641...cbb6"
Date: Mon, 23 Jan 2017 23:35:00 GMT
like image 360
Digitech Avatar asked Jan 23 '17 22:01

Digitech


1 Answers

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")
                    }
                }
            }
like image 69
Rob Avatar answered Sep 18 '22 20:09

Rob