我创建了一个NSURLCache子类,它强制在指定的时间内缓存响应。这很好用,缓存的项目按预期过期。但是,当尝试使用NSURLCache的removeCachedResponseForRequest:
方法强制删除缓存的响应时,我遇到了问题。
我希望实现的目的是允许用户强制立即重新加载远程数据。为此,我在发出请求时传递“ignoreCache”标志。我正常构建我的NSURLRequest,但要求我的NSURLCache删除给定请求的任何先前缓存的响应。但是,这似乎没有任何影响,因为缓存的结果仍然存在并在执行请求时使用。
围绕NSURLCache的文档相当稀少。 NSURLCache标头声明传递给removeCachedResponseForRequest:
的NSURLRequest用作查找关联的NSCachedURLResponse对象的键,但是关于该比较的后勤的信息很少。 NSURLCache类是否期望接收生成缓存响应的相同NSURLRequest实例,或者只是比较它所代表的NSURL?
希望有人能指出我正确的方向。
var error: NSError? = nil
var URLRequest: NSMutableURLRequest = self.operationManager.requestSerializer.requestWithMethod("GET", URLString: NSURL(string: request.URL, relativeToURL: self.operationManager.baseURL).absoluteString, parameters: request.parameters, error: &error)
URLRequest.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
// We've been asked to ignore the cache, so remove our previously cached response
if ignoreCache == true {
NSURLCache.sharedURLCache().removeCachedResponseForRequest(URLRequest)
}
这是我的NSURLCache子类中的Swift代码供参考:
// MARK: - NSURLCache
override func cachedResponseForRequest(request: NSURLRequest!) -> NSCachedURLResponse! {
var cachedResponse: NSCachedURLResponse? = super.cachedResponseForRequest(request)
if(cachedResponse != nil && cachedResponse!.userInfo != nil) {
var cacheDate: NSDate? = cachedResponse!.userInfo![self.cacheExpirationKey] as? NSDate
if(cacheDate != nil) {
var cacheDateLimit: NSDate = cacheDate!.dateByAddingTimeInterval(self.cacheExpirationInterval)
if(cacheDate!.compare(NSDate()) == NSComparisonResult.OrderedAscending) {
self.removeCachedResponseForRequest(request)
} else {
return cachedResponse
}
}
}
// Either our cached data was too old, or we don't have any that match the NSURLRequest
return nil
}
override func storeCachedResponse(cachedResponse: NSCachedURLResponse!, forRequest request: NSURLRequest!) {
var userInfo: NSMutableDictionary = NSMutableDictionary(dictionary: cachedResponse.userInfo)
userInfo[cacheExpirationKey] = NSDate().dateByAddingTimeInterval(self.cacheExpirationInterval)
var modifiedCacheResponse: NSCachedURLResponse = NSCachedURLResponse(response: cachedResponse.response, data: cachedResponse.data, userInfo: userInfo, storagePolicy: cachedResponse.storagePolicy)
super.storeCachedResponse(modifiedCacheResponse, forRequest: request)
}
答案 0 :(得分:6)
假设您使用的是iOS 8,removeCachedResponseForRequest:
无效。
请参阅http://blog.airsource.co.uk/2014/10/13/nsurlcache-ios8-broken-2/