我使用以下代码测试NSURLCache
中的行为。我在API
中初始化了AppDelegate
个实例。我根据Alamofire的文档配置了管理器,我配置了共享缓存,并指定dataTaskWillCacheResponse
以确保响应确实被缓存。
然后我调用makeRequest
来检查缓存的响应是否存在(它不应该在第一次启动时),然后我使用我的manager
使用相同的URL发出请求在整个测试过程中请求是等效的。
dataTaskWillCacheResponse
处的断点被点击,我继续,responseJSON
块已执行且Success
已完成,因此我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
表现正常,我只是遗漏了什么?提前谢谢你看看吧!
答案 0 :(得分:0)
我的回忆是大多数URL缓存更改都不是同步的。它们实际上只是在您返回到运行循环并允许发生各种异步回调之后发生。
尝试在延迟3-5秒后异步运行其余代码并查看请求是否已被删除。
如果没有解决问题,请提交错误。