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:
- https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html
- http://nshipster.com/nsurlcache/
- http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
- NSURLCache doesn't cache
- various other SO threads...
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!