4

Im trying to create some caching in my app. This is the flow: The user enter the app, the app checks weather are any changes since his last refresh, if yes, the server returns 200 and the page is refreshed. Otherwise, the server returns 304 and nothing happens. I'm using alamofire in the ios app and I tried any configuration in it but nothing helps. The real bizarre issue is that even when the server returns explicitly status code 304, my app still gets 200. This is code:

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()}

I'm trying to figure out a way to solve it for over a week! Shouldn't be so complicated Hope for help guys

Eden.F
  • 219
  • 2
  • 6
  • 2
    iOS networking code handles 3xx codes by itself. You are using HTTP status codes for incorrect situations. It's not just a number. If you want to create caching and it's not HTTP caching, use 200 and return the "cached" status in your data. – Sulthan May 13 '16 at 21:29
  • 1
    This is the expected use case. Your application code only needs to worry about 200 conditions and the library transparently handles the cached responses. – Sandy Chapman May 13 '16 at 22:28
  • This solved the issue! – Eden.F May 14 '16 at 16:50

0 Answers0