当我的Rails服务器返回304时,Alamofire响应对象返回200状态代码

gal*_*gal 8 ruby-on-rails http-status-codes ios swift alamofire

当我向rails服务器发送请求并且304未被修改时,almofire响应对象返回状态代码200.如何更改我的请求以便获取我的rails服务器返回的304状态代码?我用cocoapods安装了Alamofire.

编辑

我的代码目前(不工作):

if Reachability.isConnectedToNetwork() {
        let urlreq = NSMutableURLRequest(URL: NSURL(string: API.feedURL())!,cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
            , timeoutInterval: 5000)
        Alamofire.request(.GET, urlreq, parameters: ["category_name":category],encoding: ParameterEncoding.URL, headers: API.getHeaders())
                    .validate(statusCode: 200..<500)
                    .responseJSON { request, response, result in
                        switch result {
                        case .Success(let data):
                            let statusCode = response!.statusCode as Int!
                            if statusCode == 304 {
                                completionHandler(didModified: false, battlesArray: [])
                            } else if statusCode == 200 {
                                let json = JSON(data)
                                var battlesArray : [Battle] = []
                                for (_,subJson):(String, JSON) in json["battles"] {
                                    battlesArray.append(Battle(json: subJson))
                                }
                                completionHandler(didModified: true, battlesArray: battlesArray)
                            }
                        case .Failure(_, let error):
                            print ("error with conneciton:\(error)")
                        }
                        SVProgressHUD.dismiss()
} else {
        //nothing important
}
Run Code Online (Sandbox Code Playgroud)

这是kpsharp回答后的代码(不工作):

if Reachability.isConnectedToNetwork() {
            let urlreq = NSMutableURLRequest(URL: NSURL(string: API.feedURL()+"?category_name=Popular")!,cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData      , timeoutInterval: 5000)
    urlreq.HTTPMethod = "GET"
    let headers = API.getHeaders()
    for (key,value) in headers {
        urlreq.setValue(value, forHTTPHeaderField: key)
    }
    urlreq.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
    Alamofire.request(urlreq)
} else {
//nothing interesting
}
Run Code Online (Sandbox Code Playgroud)

编辑2

我的用于缓存的rails代码:

def index
  battles = Battle.feed(current_user, params[:category_name], params[:future_time])

  @battles = paginate battles, per_page: 50

  if stale?([@battles, current_user.id], template: false)
    render 'index'
  end
end
Run Code Online (Sandbox Code Playgroud)

谢谢

kps*_*arp 1

这已经是 Alamofire 中的一个已知问题。

cnoonAlamofire 成员推荐了这个:

很好的问题……完全有可能。您需要将 URLRequestConvertible 与 NSMutableURLRequest 结合使用来覆盖该特定请求的缓存策略。查看文档,您就会明白我的意思。

编辑:为了回应您的评论,我将提供一些快速代码,希望能够澄清问题。

所以问题是你已经缓存了响应。对于大多数用例,当您实际收到 304 时返回 200 是可以的 - 毕竟,服务器毫无问题地接受了请求,并且只是报告没有更改。然而,无论您的需求是什么,您实际上都需要查看 304,这是有效的,但我们必须忽略缓存的响应才能执行此操作。

因此,当您构建请求时,您将按照Alamofire 文档创建如下内容:

let URL = NSURL(string: "https://httpbin.org/post")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["foo": "bar"]

do {
   mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
   // No-op
}

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Run Code Online (Sandbox Code Playgroud)

这就是正常请求的样子。然而,我们需要cachePolicymutableURLRequest这样重写:

mutableURLRequest.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
Run Code Online (Sandbox Code Playgroud)

之后,只需将其踢到 Alamofire 即可发送:

Alamofire.request(mutableURLRequest)
Run Code Online (Sandbox Code Playgroud)