简单封装 AFNetworking并添加缓存

作者: Bob林 | 来源:发表于2015-11-25 13:13 被阅读1498次

    简单封装 AFNetworking 并添加缓存

    初始化缓存 10M内存 1G硬盘
    static NSURLCache* sharedCache = nil;
    +(NSURLCache*)sharedCache
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            NSString *diskPath = [NSString stringWithFormat:@"RequestCenter"];
            sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024*10
                                                        diskCapacity:1024*1024*1024
                                                            diskPath:diskPath];
        });
        return sharedCache;
    }
    

    定义一个继承NSObject的工具类,目的是方便以后换底层的网络库

    +(void)getCacheWithUrl:(NSString *)url option:(BcRequestCenterCachePolicy)option parameters:(NSDictionary *)parameters success:(BaseHttpToolSucess)success failur:(BaseHttpToolFailur)failur
    

    下面是实现的代码,我这里采用如果第一次进入没有缓存,那么直接读取服务器,如果本地有了,再存下来,每次读的都是上一次的数据,根据判断URL实现

    拿到request
    NSString *url = nil;
    NSError *serializationError = nil;
    NSString *URLString = [[NSURL URLWithString:url relativeToURL:nil] absoluteString];
    NSMutableURLRequest *request = [mgr.requestSerializer requestWithMethod:@"GET"
                                                                  URLString:URLString 
                                                                 parameters:parameters 
                                                                      error:&serializationError];
    
    拿到cachedResponse,转换成JSON
    NSCachedURLResponse *cachedResponse = [[self sharedCache] cachedResponseForRequest:request];
    if (cachedResponse) {
        id json = [NSJSONSerialization JSONObjectWithData:cachedResponse.data
                                                  options:NSJSONReadingMutableLeaves
                                                    error:nil];
        NSLog(@"缓存后的数据  %@",json);
    }
    
    当网络请求成功以后,判断一下之前是否存在这个URL
    if (![operation.response.URL isEqual:cachedResponse.response.URL]) {
        if (sucess) {
            sucess(responseObject);
            NSLog(@"第一次进入系统没有缓存%@",responseObject);
        }
    }   
    
    然后再保存下来
    NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
    cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:operation.response
                                                              data:data
                                                          userInfo:nil 
                                                     storagePolicy:NSURLCacheStorageAllowed];
    [[self sharedCache] storeCachedResponse:cachedResponse forRequest:request];
    

    Demo: https://github.com/BaiCanLin/GETPOST

    相关文章

      网友评论

      • mkvege:demo里是数据库存的
      • 扛支枪:你好,我看了一下demo,发现带缓存的get请求中,本地存在缓存了为什么还要再请求一下网络呢,只是为了更新一下最新的数据吗?
        扛支枪:@Python的日常 还有,demo中你自己写的图片缓存用了sdwebimage的东西,和sdwebimage的图片缓存有什么区别呢?可否指点一下
        Bob林:@SubStrong 对呀

      本文标题:简单封装 AFNetworking并添加缓存

      本文链接:https://www.haomeiwen.com/subject/ytzrhttx.html