我正在使用以下代码来测试 NSURLCache
中的行为。我在 AppDelegate
中初始化了一个 API
实例。我根据 Alamofire 的文档配置管理器,配置共享缓存,并分配 dataTaskWillCacheResponse
以确保响应确实会被缓存。
然后我调用 makeRequest
来检查缓存的响应是否存在(它不应该在第一次启动时),然后我使用我的 manager
发出请求相同的 URL,以便请求在整个测试过程中是等效的。
我在 dataTaskWillCacheResponse
的断点被命中,我继续,responseJSON
block 被执行并且是 Success
ful 所以我 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
行为正确而我只是遗漏了一些东西?提前感谢您查看!
我记得大多数 URL 缓存更改不是同步的。它们仅在您返回运行循环并允许发生各种异步回调后才会真正发生。
尝试在延迟 3-5 秒后异步运行其余代码,看看请求是否已被删除。
如果这不能解决问题,请提交错误。
关于ios - NSURLCache Alamofire 删除缓存的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729214/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |