AFNetworking和响应缓存处理

pax*_*axx 6 caching objective-c ios afnetworking afnetworking-2

在我的项目中,我使用AFNetworking从网上下载数据.我正在利用NSURLRequestUseProtocolCachePolicyNSURLRequest来提供用户缓存数据(如果缓存有效).这是我的代码:

请求方法:

// 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];
Run Code Online (Sandbox Code Playgroud)

可接受的内容类型方法

+ (NSSet *)acceptableContentTypes
{
    return [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html" ,nil];
}
Run Code Online (Sandbox Code Playgroud)

ServerFactory获取方法

+ (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;
}
Run Code Online (Sandbox Code Playgroud)

现在我想转换到新的逻辑:

  • 获取缓存数据
  • 如果缓存数据有效
    • 为用户提供缓存数据
    • 将If-Modified-Since标头设置为检索到的缓存数据时间戳,以发送新请求
    • 如果缓存仍然正常,则服务器响应304 Not Modified;如果有新数据,则服务器响应200 OK
    • 使用新数据更新UI
  • 如果缓存数据已过期
    • 从网上获取新数据

所以基本上我想提供缓存数据,但检查我的缓存数据是否在服务器上仍然有效,或者是否有新数据要下载.有没有办法实现这个目标?我试图与setCacheResponseBlockAFHTTPRequestOperation,但我不能获取缓存数据的时间戳.有一种"更聪明"的方法吗?

pfr*_*ank 1

查看AFNetworking:如何知道响应是否正在使用缓存?304或200

“我找到了一种方法,将修改日期与请求关联起来,然后在 AFNetWorking 答复我时比较该日期。

没有我想象的那么干净,但是有效......”