有没有一种方法可以使用Alamofire 4检测304 Not Modified响应?我发现即使服务器响应为304,Alamofire response.statusCode始终为200。

网络通话设置:

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响应 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;
} }

服务器响应
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

最佳答案

由于NSURLSessions的默认行为是通过始终返回200个响应(而不是实际重载数据)从缓存的304个响应中抽象出来,因此我首先必须按以下方式更改cachingPolicy:

urlRequest.cachePolicy = .reloadIgnoringCacheData

然后,我调整了validate函数的状态代码以接受3xx响应并相应地处理了这些代码:
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")
                    }
                }
            }

关于ios - 如何使用Alamofire检测304状态代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41816606/

10-13 04:48