NSURLCache 不适用于 NSURLSession

NSURLCache not working with NSURLSession

我在 iOS 8.0 Swift 应用程序中遇到缓存问题。这是我所做的:

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
}

我有一个自定义视图,运行在初始化时使用此代码:

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

然后我 运行 当我点击一个按钮时这个代码:

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

我的 localhost/test url 是一个简单的端点,我已将其设置为 return 随机 JSON,并包括一个 Cache-Control header 之类的这个:

Cache-Control:max-age=600

我的问题是请求永远不会写入缓存。我也尝试过将 "UseProtocolCachePolicy" 更改为 "ReturnCacheDataElseLoad",但仍然不会写入缓存。

关键在于:如果我使用 NSURLConnection(而不是 NSURLSession)进行一次调用,它就会被写入缓存。然后所有调用都可以从缓存中加载。我该如何解决这个问题?

NSURLCache 和 NSURLSession 目前看起来充其量是错误的,并且可能已损坏。我不需要后台下载或类似的东西,所以我选择使用 Cash: https://github.com/nnoble/Cash 。它非常适合我的需要。