NSURLCache无法使用NSURLSession

时间:2015-01-07 22:36:16

标签: ios swift nsurlsession nsurlcache

我在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是一个简单的端点,我已设置为返回随机JSON,并包含一个Cache-Control标头,如下所示:

Cache-Control:max-age=600

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

这是踢球者:如果我使用NSURLConnection(而不是NSURLSession)进行一次调用,它就会被写入缓存。然后所有调用从缓存加载就好了。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

NSURLCache和NSURLSession目前似乎充满了错误,并且可能已经破裂。我不需要后台下载或类似的东西,因此我选择使用Cash:https://github.com/nnoble/Cash。它完全符合我的需求。