我在我的iOS 8.0SWIFT应用程序中缓存有问题。以下是我所做的:
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:max-age=600我的问题是,请求永远不会被写入缓存。我也尝试过将"UseProtocolCachePolicy“更改为"ReturnCacheDataElseLoad",但仍然不会写入缓存。
下面是问题所在:如果我使用NSURLConnection (而不是NSURLSession)进行一次调用,它就会被写到缓存中。然后,所有的调用都会从缓存中加载。我该怎么解决这个问题?
发布于 2015-01-10 22:31:24
目前看来,NSURLCache和NSURLSession充其量都是有问题的,而且很可能已经坏了。我不需要背景下载之类的东西,所以我选择使用Cash:https://github.com/nnoble/Cash。它非常适合我的需要。
https://stackoverflow.com/questions/27829912
复制相似问题