AFNetworking和响应缓存处理

6
在我的项目中,我使用AFNetworking从网络上下载数据。我在我的NSURLRequest上利用了NSURLRequestUseProtocolCachePolicy来提供用户缓存的数据(如果缓存有效)。以下是我的代码:
请求方法:
// 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获取方法

+ (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;
}

现在我想转到新的逻辑:
- 获取缓存的数据 - 如果缓存的数据仍有效 - 使用缓存的数据为用户提供服务 - 用检索到的缓存数据时间戳设置 If-Modified-Since 请求头发送新请求 - 如果缓存仍然有效,服务器响应 304 Not Modified ,如果有新数据,则响应 200 OK - 使用新数据更新 UI - 如果缓存数据已过期 - 从网络获取新数据
基本上我想使用缓存的数据,但要检查服务器上的缓存数据是否仍然有效或者是否有新的数据需要下载。有没有方法可以实现这个?我尝试使用 AFHTTPRequestOperation 上的 setCacheResponseBlock ,但是无法获取缓存数据的时间戳。有没有更"聪明"的方法来做这件事?

我正在使用AFNetworking 2.0。 - paxx
看看这个话题,它可能会对你有所帮助:https://dev59.com/T2ct5IYBdhLWcg3wUb1-#21556002 - Darrarski
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接