3
votes

I'm seeing weird behaviors when using NSURLCache and exhausted all options but posting here... so here it is:

I'm trying to implement NSURLCache as underlying caching mechanism in combination with NSURLSession. And using Charles and simple println() I observe that no matter what I do, my app continues to go back to the server and re-requests previous requests.

I validated that my server sends the following headers consistently:

 Cache-Control:public, max-age=31449600
 Content-Length:74289
 Content-Type:image/jpeg
 ETag:"abcdf"
 Expires:Sun, 03 Jan 2016 20:58:01 GMT
 Last-Modified:Sat, 09 Nov 2013 08:05:53 GMT

Yet when I make the following request:

let req = NSURLRequest(URL: NSURL(string: URLString)!, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 15)

NSURLSession's willCacheResponse: delegate method doesn't get called at all:

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse!) -> Void) {

However, when simply requesting NSURLRequest(URL: NSURL(string: URLString)!) without specifying specific cachePolicy, then willCacheResponse: does get called. Nevertheless, the next time the same request is made, the app goes back to server...

I don't do any response object modifications in any NSURLSession delegate methods and my requests are all HTTP GET.

What am I missing?

I've read a lot that's out there on NSURLCache:

Setup: Xcode6.1, Swift, iOS8+

Edit: I pushed a basic example to github to show my problem: https://github.com/opfeffer/nsurlcache

Check it out and let me know what I'm doing wrong!

1
Can we see a small, complete example of code that shows the problem? It would be helpful, for example, to know how you're actually making the request, and creating the session, including the session configuration object particularly.Matt Gibson
What's the URL that you are requesting? Are you using GET or POST? Can you see from the logs what the client is sending to the server? Are any firewalls in the way causing problems?AlBlue
@MattGibson: I added a sample app to github. Check it out! THANKS!!!opfeffer

1 Answers

0
votes

I see your GET request has parameters, and for that I think we are facing the same situation.

I reached a solution overriding NSURLCache doing some adjustments and accessing the underlying DB, you can see it here:

https://github.com/JCardenete/NTURLCache/tree/master/NTURLCache

NSURLCache - Disk caching for GET request with parameters not working