Search code examples
iosswiftnsurlsessionnsurlcache

NSURLCache not working with NSURLSession


I am having trouble with caching in my iOS 8.0 Swift app. Here is what I have done:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let URLCache = NSURLCache(memoryCapacity: 500 * 1024 * 1024, diskCapacity: 500 * 1024 * 1024, diskPath: nil)
    NSURLCache.setSharedURLCache(URLCache)
    return true
}

I have a custom view that runs this code on initialization:

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.URLCache = NSURLCache.sharedURLCache()
config.requestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy
session = NSURLSession(configuration: config)

Then I run this code when I hit a button:

let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/test")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 100)
session!.dataTaskWithRequest(request, completionHandler: { (data, res, error) -> Void in
    let test = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
    println(test)
}).resume()

My localhost/test url is a simple endpoint I have setup to return random JSON, and includes a Cache-Control header like this:

Cache-Control:max-age=600

My problem is that the request never gets written to the cache. I have also tried changing "UseProtocolCachePolicy" to "ReturnCacheDataElseLoad", but still won't write to the cache.

Here is the kicker: if I use NSURLConnection (instead of NSURLSession) to make the call once, it gets written to the cache. Then all of calls load from the cache just fine. How do I fix this?


Solution

  • NSURLCache and NSURLSession currently appear to be buggy at best, and possibly broken. I don't need background downloads or anything like that, so I opted to use Cash: https://github.com/nnoble/Cash . It works perfectly for my needs.