在我的项目中,我正在使用AFNetworking从网上下载数据。我在NSURLRequestUseProtocolCachePolicy
上利用NSURLRequest
来提供用户缓存数据(如果缓存有效)。这是我的代码:
请求方法:
// create NSURL request
NSURLRequest *request = [ServerFactory URLGETRequestWithURL:url];
//creating AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//set serializaer
operation.responseSerializer = [AFJSONResponseSerializer serializer];
//need to specify that text is acceptable content type, otherwise the error occurs
operation.responseSerializer.acceptableContentTypes = [MyRepository acceptableContentTypes];
//running fetch request async
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//parse data
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//error handling
}];
//start async operation
[operation start];
可接受的内容类型方法
+ (NSSet *)acceptableContentTypes
{
return [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html" ,nil];
}
ServerFactory get methods
+ (NSURLRequest *)URLGETRequestWithURL:(NSString *)URL
{
NSMutableURLRequest *request = [[ServerFactory URLRequestWithURL:URL] mutableCopy];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:@"GET"];
return request;
}
+ (NSURLRequest *)URLRequestWithURL:(NSString *)URL
{
// creating NSURL to give to NSURLRequest
NSURL *theURL = [NSURL URLWithString:URL];
//adding service version in http header
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:theURL];
[request addValue:HTTP_HEADER_VERSION_VALUE forHTTPHeaderField:HTTP_HEADER_VERSION_NAME];
//returing request
return request;
}
现在我想转换到新逻辑:
所以基本上我想提供缓存数据,但检查我的缓存数据是否在服务器上仍然有效,或者是否有新数据要下载。有没有办法实现这个目标?我在setCacheResponseBlock
上尝试使用AFHTTPRequestOperation
,但我无法获得缓存数据时间戳。有一种“更聪明”的方法吗?
答案 0 :(得分:1)
查看AFNetworking : How to know if response is using cache or not ? 304 or 200
“我找到了一种方法,通过保存修改日期与请求相关联,并在AFNetWorking回答我时比较这个日期。
不像我想的那样干净,但有效......“