我正在尝试让我的应用使用我服务器提供的Last-Modified
标头。
问题是应用程序不断缓存来自服务器的响应,我一次又一次地尝试清除缓存,不允许它缓存响应等,但NOTHING正在工作。我尝试过以下方法:
代表AFNetworking
:
- (AFHTTPRequestOperationManager *)manager {
if (!_manager) {
_manager = [AFHTTPRequestOperationManager manager];
_manager.responseSerializer = [AFJSONResponseSerializer serializer];
[_manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
}
return _manager;
}
设置NSURLRequestReloadIgnoringLocalCacheData
无效。
我在delegate
中尝试了这个:
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
我甚至尝试将它们设置为0以消除所有缓存的可能性。仍然没有奏效。
我还尝试按以下方式删除缓存:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeCachedResponsesSinceDate:last];
即使这样也行不通。当我从服务器获得新响应时,它只是再次从缓存重新加载!还有什么我还没试过会有帮助吗?当我删除服务器响应的Last-Modified
标头时,一切正常。但这不是正确的解决方案。
我也读过以下内容:
http://blog.originate.com/blog/2014/02/20/afimagecache-vs-nsurlcache/
答案 0 :(得分:0)
我建议尝试添加这个modyfied方法 - (NSCachedURLResponse *)连接:(NSURLConnection *)连接willCacheResponse:(NSCachedURLResponse *)cachedResponse
as:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if (self.cacheResponse) {
//we comment this line and add return nil return self.cacheResponse(connection, cachedResponse);
return nil;
} else {
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
}
另一个黑客应该工作:
[requestOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
return nil;
}];
其中requestOperation是您的网络请求操作。
更多来自SDWebimage的灵感
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
// Prevents caching of responses
return nil;
}
else {
//we modify also this to return nil return cachedResponse;
return nil;
}
}