我使用下面的代码来测试NSURLCache中的行为。我在API中初始化一个AppDelegate实例。我根据Alamofire的文档配置管理器,配置共享缓存,并分配dataTaskWillCacheResponse以确保响应确实被缓存。
然后调用makeRequest,检查缓存的响应是否存在(在第一次启动时不应该),然后使用manager使用相同的URL发出请求,以便在整个测试过程中该请求等效。
我在dataTaskWillCacheResponse的断点被击中,我继续,responseJSON块被执行,并且是Successful,所以我使用请求进行performTests。
下面是代码:
import Alamofire
class API: Manager.SessionDelegate {
var manager: Manager!
override init() {
super.init()
manager = Manager(session: urlSession(), delegate: self)
configureCache(memoryCapacityMB: 5, diskCapacityMB: 25)
manager.delegate.dataTaskWillCacheResponse = { urlSession, dataTask, cachedResponse in
// Placing a breakpoint here confirms that the response is going to be cached
return cachedResponse
}
}
private func urlSession() -> NSURLSession {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}
private func configureCache(memoryCapacityMB memory: Int, diskCapacityMB disk: Int) {
let memoryCapacity = memory * 1024 * 1024
let diskCapacity = disk * 1024 * 1024
let sharedCache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: nil)
NSURLCache.setSharedURLCache(sharedCache)
}
// MARK: Request
func makeRequest() {
// The response should be nil on the first launch since nothing has been cached
let request = NSURLRequest(URL: NSURL(string: "http://jsonplaceholder.typicode.com/posts")!)
let response = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
print(response)
manager.request(.GET, request.URLString).responseJSON { response in
switch response.result {
case .Success:
self.performTests(with: response.request!)
case .Failure:
break
}
}
}
func performTests(with request: NSURLRequest) {
// Should exist
var response = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
print(response)
// And it does: good!
// Remove the cached resopnse and check if it exists
NSURLCache.sharedURLCache().removeCachedResponseForRequest(request)
response = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
print(response)
// And it does: bad!
// Try removing all cached responses and check if it exists
NSURLCache.sharedURLCache().removeAllCachedResponses()
response = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
print(response)
// And it doesn't: good! But odd...
}
},那么如何删除单个请求的缓存响应呢?,这是意外的行为吗?还是NSURLCache的行为是正确的,而我只是遗漏了什么?提前感谢您的光临!
发布于 2016-09-24 19:46:26
我记得大多数URL缓存更改都是不同步的。它们实际上只有在返回运行循环并允许发生各种异步回调之后才会发生。
尝试在延迟3-5秒后异步运行其余代码,并查看请求是否已被删除。
如果这不能解决问题,请提交一个bug。
https://stackoverflow.com/questions/38729214
复制相似问题