AFNetworking:如何知道响应是否正在使用缓存? 304或200 [英] AFNetworking : How to know if response is using cache or not ? 304 or 200
问题描述
我找不到任何问题的答案,可能是我错过了什么...
I can't find any answer to my question, may be I miss something...
当我要求提供网址时,我需要知道是否响应来自缓存或来自网络。
When I ask for a url, I need to know if the response comes from the cache or from the net.
状态代码是304还是200? (但 AFNetworking
总是回复200)
Is the status code 304 or 200 ? (but AFNetworking
always responde 200)
使用 ASIHTTPRequest
我曾经从 ASIHTTPRequest
检查 didUseCachedResponse
,这很完美。
With ASIHTTPRequest
I used to check "didUseCachedResponse
" from ASIHTTPRequest
, this was perfect.
推荐答案
我想我找到了一个解决方案来确定是否使用AFNetworking 2.0从缓存返回响应。我发现每次从服务器返回一个新的响应(状态200,而不是304)时, cacheResponseBlock
这是 AFHTTPRequestOperation的属性
被调用。如果响应应缓存,则块应返回 NSCachedURLResponse
,否则返回nil。这样您就可以过滤响应并仅缓存部分响应。在这种情况下,我正在缓存来自服务器的所有响应。诀窍是,当服务器发送304并从缓存加载响应时,将不会调用此块。所以,这是我正在使用的代码:
I think I found a solution to determine if response was returned from cache or not using AFNetworking 2.0. I found out that each time a new response is returned from the server (status 200, not 304) the cacheResponseBlock
which is a property of AFHTTPRequestOperation
is called. The block should return NSCachedURLResponse
if response should be cached or nil if it shouldn't. That's way you can filter responses and cache only some of them. In this case, I am caching all responses that comes from the server. The trick is, that when server sends 304 and response is loaded from cache, this block won't be called. So, this is the code I am using:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
BOOL __block responseFromCache = YES; // yes by default
void (^requestSuccessBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseFromCache) {
// response was returned from cache
NSLog(@"RESPONSE FROM CACHE: %@", responseObject);
}
else {
// response was returned from the server, not from cache
NSLog(@"RESPONSE: %@", responseObject);
}
};
void (^requestFailureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"ERROR: %@", error);
};
AFHTTPRequestOperation *operation = [manager GET:@"http://example.com/"
parameters:nil
success:requestSuccessBlock
failure:requestFailureBlock];
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
// this will be called whenever server returns status code 200, not 304
responseFromCache = NO;
return cachedResponse;
}];
这个解决方案对我有用,到目前为止我还没有发现任何问题。但是,如果您对我的解决方案有更好的想法或反对意见,请随时发表评论!
This solution works for me and I haven't found any issues so far. But, if you have a better idea or some objections against my solution, feel free to comment!
这篇关于AFNetworking:如何知道响应是否正在使用缓存? 304或200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!