使用ETag进行AFNetworking缓存

时间:2015-08-04 14:42:58

标签: ios objective-c caching afnetworking nsurlcache

我在使用AFNetworking和ETag值实现缓存时遇到问题。我的服务器为每个请求返回Cache-Control和ETag标头值。但是,如果我对同一资源发出第二次请求,AFNetworking将不会添加ETag。我应该为每个响应手动保存etag并将其附加到下一个请求吗?

在app delegate中我设置了缓存对象:

 NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
 [NSURLCache setSharedURLCache:URLCache];

另外,我正在使用AFHTTPRequestSerializer的默认缓存策略。

任何想法是什么问题?也许我不明白http缓存的想法。据我所知,它应该是透明的,我所要做的就是为每个响应附加ETag和Cache-Control标头。

修改

响应的标题如下所示:

"Cache-Control" = "max-age=3600";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 05 Aug 2015 07:52:33 GMT";
Etag = "W/f6c8a0f47deb7db0eeea3069061de9ab";
Expires = "Wed, 05 Aug 2015 08:52:30 GMT";
"Last-Modified" = "Wed, 05 Aug 2015 08:52:30 GMT";
Server = "cloudflare-nginx";
Vary = "Accept-Encoding";
"cf-ray" = "2110ec564bde0afc-WAW";
"x-cache-id" = "api_3447fddb8680ed5d082ae871e95214dc";
"x-powered-by" = "PHP/5.5.19";
"x-whom" = "www-stage02-b"

1 个答案:

答案 0 :(得分:0)

要检查AFHTTPRequestOperation是否来自缓存,您可以使用以下代码:

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
                                                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest* mutableRequest = [request mutableCopy];
    BOOL __block responseFromCache = YES;

    AFHTTPRequestOperation* operation = [super HTTPRequestOperationWithRequest:mutableRequest
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSString* source = responseFromCache ? @"CACHE" : @"SERVER";
        NSLog(@"Request from %@", source);
        success(operation, responseObject);
    }
    failure:nil];

    [operation setCacheResponseBlock:
     ^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
         responseFromCache = NO;
         return cachedResponse;
     }];

    return operation;
}

确保在应用程序开始运行时也启用了NSURLCache。

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:5 * 1024 * 1024
                                                     diskCapacity:50 * 1024 * 1024
                                                         diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];