为AFNetworking 3.x实现自定义缓存 [英] Implement custom cache for AFNetworking 3.x

查看:77
本文介绍了为AFNetworking 3.x实现自定义缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在编写一个iOS API,以使用AFNetworking 3.x从服务器获取数据。我的服务器不支持缓存。此服务器标头

Hi I'm writing a IOS api to fetch data from server using AFNetworking 3.x My Server does not support caching. This this server header

Connection →Keep-Alive
Content-Length →4603
Content-Type →text/html; charset=UTF-8
Date →Wed, 10 Aug 2016 04:03:56 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.18 (Unix) OpenSSL/1.0.1e-fips PHP/5.4.45
X-Powered-By →PHP/5.4.45

我想构建自定义API以启用缓存(例如,请求和响应应缓存10秒,以便如果用户发出相同的请求,则使用缓存数据。如果缓存过期的应用程序将再次重新下载) )

I want to build custom API to enable cache (for example request and response should be cache for 10 second so that if user make same request, cache data is used. If cache expired app will then re download again)

我的 AFNetworking Singleton

My AFNetworking Singleton

#pragma mark - Shared singleton instance

+ (ApiClient *)sharedInstance {
    static ApiClient *sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:SINGPOST_BASE_URL] sessionConfiguration:sessionConfiguration];

    return sharedInstance;
}

- (id)initWithBaseURL:(NSURL *)url
{
    if ((self = [super initWithBaseURL:url])) {
        self.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    return self;
}

我的JSON请求

- (void)sendJSONRequest:(NSMutableURLRequest *)request
                success:(void (^)(NSURLResponse *response, id responseObject))success
                failure:(void (^)(NSError *error))failure {

    self.responseSerializer.acceptableContentTypes = [AFHTTPResponseSerializer serializer].acceptableContentTypes;
    self.requestSerializer.timeoutInterval = 5;
    self.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

        [self setDataTaskWillCacheResponseBlock:^NSCachedURLResponse * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSCachedURLResponse * _Nonnull proposedResponse) {
            return [[NSCachedURLResponse alloc] initWithResponse:proposedResponse.response
                                                            data:proposedResponse.data
                                                        userInfo:proposedResponse.userInfo
                                                   storagePolicy:NSURLCacheStorageAllowed];
        }];

    NSURLSessionDataTask *dataTask = [ApiClient.sharedInstance dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error URL: %@",request.URL.absoluteString);
            NSLog(@"Error: %@", error);
            failure(error);
        } else {
            NSDictionary *jsonDict  = (NSDictionary *) responseObject;
            success(response,jsonDict);
            NSLog(@"Success URL: %@",request.URL.absoluteString);
            NSLog(@"Success %@",jsonDict);
        }
    }];
    [dataTask resume];

}

如何修改以下代码以启用缓存请求和响应(我希望响应保持10秒钟左右)(如果没有互联网连接,则为1天),非常感谢您的帮助。

How to modify the bellow code to enable caching request and response (I want response to be keep like 10 sec) (Or 1 day if no internet connection) Any help is much appreciate. Thanks!

[self setDataTaskWillCacheResponseBlock:^NSCachedURLResponse * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSCachedURLResponse * _Nonnull proposedResponse) {
            return [[NSCachedURLResponse alloc] initWithResponse:proposedResponse.response
                                                            data:proposedResponse.data
                                                        userInfo:proposedResponse.userInfo
                                                   storagePolicy:NSURLCacheStorageAllowed];
        }];


推荐答案

代替

            return [[NSCachedURLResponse alloc] initWithResponse:proposedResponse.response

do

            NSMutableDictionary *dictionary = [proposedResponse.response.allHeaderFields mutableCopy];
            dictionary[@"Cache-Control" = ...
            NSHTTPURLResponse *modifiedResponse =
              [[NSHTTPURLResponse alloc initWithURL:proposedResponse.response.URL
                                         statusCode:proposedResponse.response.statusCode
                                        HTTPVersion:@"HTTP/1.1"
                                       headerFields:modifiedHeaders];

            [modifiedResponse 
            return [[NSCachedURLResponse alloc] initWithResponse:modifiedResponse

请注意,无法从原始请求中获取HTTP版本。我很确定我已经提交了一个有关此问题的错误。我也很确定它不会对任何事物产生任何影响,并且我认为它甚至都不会存储在基础对象中,因此它可能并不重要。

Note that it is not possible to retrieve the HTTP version from the original request. I'm pretty sure I filed a bug about that. I'm also pretty sure that it doesn't have any effect on anything, and I don't think it even gets stored in the underlying object, so it probably doesn't matter.

这篇关于为AFNetworking 3.x实现自定义缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆