如何使用Alamofire检测304 statusCode

时间:2017-01-23 22:10:20

标签: ios swift swift3 alamofire

有没有办法用Alamofire 4检测304 Not Modified响应?我发现Alamofire response.statusCode总是200,即使服务器用304响应。

网络电话设置:

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响应标题

<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

2 个答案:

答案 0 :(得分:4)

由于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")
                    }
                }
            }

答案 1 :(得分:0)

您可以按照here概述的Alamofire使用手动回复验证。

Alamofire.request("https://httpbin.org/get")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseData { response in
        switch response.result {
        case .success:
            print("Validation Successful")
        case .failure(let error):
            print(error)
        }
    }