Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire response object return 200 status code when my Rails server return 304

When I send a request to my rails server and get 304 not modified, almofire response object return status code 200. How can I change my request so I will get the 304 status code my rails server returns? I installed Alamofire using cocoapods.

EDIT

This my code currently (not working):

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
}

This is the code after kpsharp answer (not working):

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
}

EDIT 2

My rails code for caching:

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

Thanks

like image 461
gal Avatar asked May 06 '16 16:05

gal


1 Answers

This is a known issue in Alamofire already.

cnoon, an Alamofire member, recommended this:

Great question...totally possible already. You need to use the URLRequestConvertible in combination with an NSMutableURLRequest to override the cachePolicy for that particular request. Check out the documentation and you'll see what I mean.

EDIT: In response to your comment, I'll provide some quick code that hopefully will clear things up.

So the issue is that you have cached response. For most use cases, returning a 200 when you actually received a 304 is fine - after all, the server accepted the request without issue and is just reporting that there was no change. However, for whatever your needs are, you actually need to see the 304, which is valid but we have to ignore the cached response to do so.

So when you are building your request, you would follow the Alamofire documentation to create something like this:

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

That's how a normal request would look. However, we need to override the cachePolicy for the mutableURLRequest like so:

mutableURLRequest.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData

After that, just kick it to Alamofire to send off:

Alamofire.request(mutableURLRequest)
like image 142
kpsharp Avatar answered Oct 27 '22 01:10

kpsharp