9

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

gal
  • 929
  • 4
  • 21
  • 39
  • Please add some code to your question.. – Alessandro Ornano May 09 '16 at 06:45
  • If you've found the solution, you should answer your own question with the details and accept it so future SO readers know what worked and why. – kpsharp May 09 '16 at 22:11
  • I didn't found the solution... Still not working – gal May 10 '16 at 07:19
  • @gal Can you try turning off all caching? I want to verify that this is the problem. Use `config.action_controller.perform_caching = false` in your Rails env. – kpsharp May 10 '16 at 17:55
  • I tried to change it to "true" and "false" and both don't work.. – gal May 10 '16 at 18:07
  • @gal what http request headers are you using i.e. `API.getHeaders()` ? I would recommend comparing the requests, one from iOS device and another from any rest client. – sargeras May 12 '16 at 12:00

1 Answers1

1

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)
kpsharp
  • 455
  • 3
  • 10
  • Hey, I don't understand this explanation can you explain more please? – gal May 06 '16 at 18:36
  • Just tested it and this solution does not work... do you know maybe what the problem is? thanks :) – gal May 07 '16 at 12:08
  • @gal Have you tried invalidating the cache server side yet? – kpsharp May 09 '16 at 19:36
  • What do you mean by "invalidating the cache server side"? I see in the logs that I get 304 status code. – gal May 09 '16 at 19:56
  • Let's start here: do you have control of the server? – kpsharp May 09 '16 at 20:12
  • Yes, Ruby on rails server that I built – gal May 09 '16 at 20:13
  • Okay, do a fresh session, and edit your question to include all of the logs involved while it's performing the work on the server. – kpsharp May 09 '16 at 20:38
  • I found the problem, The server return the etag with apostrophes like this - "ac4a8905338a2a4dc0e5e452a9512e3d", this is really weird because we used the official rails function for caching. – gal May 09 '16 at 21:05
  • desperate here :/ any ideas? – gal May 10 '16 at 21:16
  • I think at this point, you should repost the question on with a rails tag. I agree with Alessandro Ornano above - this is a server configuration issue. – kpsharp May 10 '16 at 22:40