【问题标题】:Implement custom cache for AFNetworking 3.x为 AFNetworking 3.x 实现自定义缓存
【发布时间】:2016-12-16 08:18:10
【问题描述】:

您好,我正在编写一个 IOS api 来使用 AFNetworking 3.x 从服务器获取数据我的服务器不支持缓存。这个这个服务器头

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 秒,这样如果用户发出相同的请求,就会使用缓存数据。如果缓存过期的应用程序将重新下载)

我的AFNetworking单身

#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 天)非常感谢任何帮助。谢谢!

[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];
        }];

【问题讨论】:

    标签: ios caching afnetworking


    【解决方案1】:

    代替

                return [[NSCachedURLResponse alloc] initWithResponse:proposedResponse.response
    

                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 版本。我很确定我为此提交了一个错误。我也很确定它对任何东西都没有任何影响,而且我认为它甚至不会存储在底层对象中,所以它可能无关紧要。

    【讨论】:

    • 您好,感谢您的帮助。最理想的是抓取响应头。为@“缓存控制”添加字段?正确的方法是例如:dictionary[@"Cache-Control" = @"max-age = 120, public"。我们可以为 HTTPVersion 传递 nil 吗?它可以在 HTTPS 上运行吗?
    • 第一个问题是;您只需将字符串设置为该标题字段的值。我不知道为 HTTP 版本传递 nil 。据我所知,HTTPS 对缓存没有任何影响。
    • 感谢您的澄清将实施。如何设置磁盘缓存和内存缓存容量。默认值是多少。这足以满足正常的网络流量(JSON、图像...)吗?
    • 我对此没有意见。这在很大程度上取决于您的应用程序在做什么。最好的办法可能是尝试各种尺寸,看看它在您的特定应用中的表现。
    • 但我看不出我们如何更改缓存大小(磁盘缓存和内存缓存)
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2010-09-23
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多