美文网首页
利用YYCache和AFN实现网络数据缓存

利用YYCache和AFN实现网络数据缓存

作者: 搬运工开发者 | 来源:发表于2019-06-01 17:59 被阅读0次

    背景

    • 网络比较差的情况为了提高用户体验需要先显示旧的数据,拿到新数据在更新
    • 对于短时间内变化不大的数据,用户重复获取数据不仅浪费浏览也增大服务器的压力

    xmind图

    网络请求.png

    项目类

    主要分为缓存类HZNetWorkCache、配置类HZNetworkConfig、网络请求类HZNetworkManager

    HZNetWorkCache

    • 缓存类比较简单,主要实现数据的存储,基于YYCache
    • 将网络请求的连接和提交的参数拼接作为key
    • 将网络请求后台返回的数据作为value
    • 设置缓存时间,每次读取缓存都先校验缓存时间的有效性
      1)将网络请求的连接和提交的参数、"_HZNetworkTimeOut"(常量,可随意)拼接作为key
      2)将缓存时间作为value
    HZNetWorkCache代码

    ps:这个类的代码主要从网上找的,稍加了修改

    static NSString *const HZNetworkCache = @"HZNetworkCache";
    static NSString *const HZNetworkTimeOut = @"HZNetworkTimeOut";
    
    @implementation HZNetWorkCache
    static YYCache *_dataCache;
    
    + (void)initialize {
        _dataCache = [YYCache cacheWithName:HZNetworkCache];
    }
    
    
    /**
     异步缓存网络数据,根据请求的 URL与parameters
     做KEY存储数据, 这样就能缓存多级页面的数据
     
     @param httpData 服务器返回的数据
     @param URL 请求的URL地址
     @param parameters 请求的参数
     
     */
    + (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters {
        NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
        [_dataCache setObject:httpData forKey:cacheKey withBlock:nil];
        //缓存请求过期时间
        [self setCacheInvalidTimeWithCacheKey:cacheKey];
    }
    
    
    /**
     根据请求的 URL与parameters 同步取出缓存数据
     
     @param URL 请求的URL
     @param parameters 请求的参数
     @param cacheValidTime 数据缓存时间
     @return 缓存的数据
     
     */
    + (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters cacheValidTime:(NSTimeInterval)cacheValidTime {
        NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
        id cache = [_dataCache objectForKey:cacheKey];
    
        if (!cache) {
            return nil;
        }
    
        if ([self verifyInvalidCache:cacheKey resultCacheDuration:cacheValidTime]) {
            return cache;
        }else{
            [_dataCache.diskCache removeObjectForKey:cacheKey];
            NSString *cacheDurationKey = [NSString stringWithFormat:@"%@_%@",cacheKey, HZNetworkTimeOut];
            [_dataCache.diskCache removeObjectForKey:cacheDurationKey];
            return nil;
        }
    
    }
    
    /**
     获取缓存,不考虑缓存是否有效
     
     @param URL 请求的URL
     @param parameters 请求的参数
     @return 缓存的数据
     
     */
    + (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters {
        NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
        return [_dataCache objectForKey:cacheKey];
    }
    
    /**
     获取网络缓存的总大小 bytes(字节)
     
     @return 大小
     */
    + (NSInteger)getAllHttpCacheSize {
        return [_dataCache.diskCache totalCost];
    }
    
    /**
     删除所有网络缓存
     */
    + (void)removeAllHttpCache {
        [_dataCache.memoryCache removeAllObjects];
        [_dataCache.diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) {
            
        } endBlock:^(BOOL error) {
            
        }];
    }
    
    /**
     删除缓存
     
     @param url url
     @param parameters 参数
     */
    + (void)removeHttpCacheWithUrl:(NSString *)url parameters:(NSDictionary *)parameters {
        NSString *cacheKey = [self cacheKeyWithURL:url parameters:parameters];
        NSString *cacheTimeKey = [NSString stringWithFormat:@"%@_%@", cacheKey, HZNetworkTimeOut];
        [_dataCache.memoryCache removeObjectForKey:cacheKey];
        [_dataCache.diskCache removeObjectForKey:cacheKey withBlock:^(NSString * _Nonnull key) {
    
        }];
        [_dataCache.memoryCache removeObjectForKey:cacheTimeKey];
        [_dataCache.diskCache removeObjectForKey:cacheTimeKey withBlock:^(NSString * _Nonnull key) {
            
        }];
    }
    
    
    /**
     拼接key
    
     @param URL url
     @param parameters 提交的参数
     @return key
     */
    + (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
        if(!parameters || parameters.count == 0){return URL;};
        // 将参数字典转换成字符串
        NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
        NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
        NSString *cacheKey = [NSString stringWithFormat:@"%@%@", URL, paraString];
    
        return [NSString stringWithFormat:@"%@",cacheKey];
    }
    
    
    
    /** 存入缓存创建时间 */
    + (void)setCacheInvalidTimeWithCacheKey:(NSString *)cacheKey {
        NSString *cacheDurationKey = [NSString stringWithFormat:@"%@_%@",cacheKey, HZNetworkTimeOut];
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        [_dataCache setObject:@(nowTime) forKey:cacheDurationKey withBlock:nil];
    }
    
    /** 判断缓存是否有效,有效则返回YES */
    + (BOOL)verifyInvalidCache:(NSString *)cacheKey resultCacheDuration:(NSTimeInterval )resultCacheDuration {
        //获取该次请求失效的时间戳
        NSString *cacheDurationKey = [NSString stringWithFormat:@"%@_%@",cacheKey, HZNetworkTimeOut];
        id createTime = [_dataCache objectForKey:cacheDurationKey];
        NSTimeInterval createTime1 = [createTime doubleValue];
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        if ((nowTime - createTime1) < resultCacheDuration) {
            return YES;
        }
        return NO;
    }
    

    HZNetworkConfig

    该类主要用于网络请求配置

    • baseURL(NSString)网络请求基链
    • requestSerializer(AFHTTPRequestSerializer)请求的一些配置(默认不变的信息)
    • responseSerializer(AFHTTPResponseSerializer)对返回的数据进行序列化,默认使用 AFJSONResponseSerializer
    • builtinHeaders (NSMutableDictionary)请求的头部通用配置
    • builtinBodys(NSMutableDictionary)请求体通用配置
    • timeoutInterval(NSTimeInterval) 请求超时时间设置,默认10秒
    • resultCacheDuration(NSInteger)设置缓存时间,默认7246060秒(724小时)。如果 <= 0,表示不启用缓存。单位为秒,表示对于一个请求的结果缓存多长时间
    • requestCachePolicy(HZRequestCachePolicy)缓存策略, 默认是HZRequestCacheOrLoadToCache
    • (^ resposeHandle)(NSURLSessionTask *dataTask, id responseObject) 对请求返回的数据做统一的处理,比如token失效、重新登录等等操作。

    缓存策略

    typedef NS_ENUM(NSUInteger, HZRequestCachePolicy) {
        /** HZRequestCacheOrLoadToCache, HZRequestCacheAndLoadToCache, HZRequestLoadToCache这三种方式如果网络请求失败且有缓存数据则直接返回缓存数据(不管缓存数据是否有效),如果不存在缓存则直接返回failured */
        HZRequestCacheOrLoadToCache,//如果缓存有效则直接返回缓存,不再load。缓存失效则load返回,且缓存数据,用于同一个网络请求在一定时间内不多次发起网络请求
        HZRequestCacheDontLoad,//如果缓存有效则直接返回缓存,缓存失效则返回nil,不再load
        HZRequestCacheAndLoadToCache,//如果缓存有效则直接返回缓存,并且load且缓存数据。缓存失效则load返回,且缓存数据
        HZRequestLoadToCache,//直接load并返回数据,且缓存数据,如果load失败则读取缓存数据
        HZRequestLoadDontCache,//直接load并返回数据,不缓存数据,如果load失败则直接抛出Error
    };
    
    const CGFloat HZRequestTimeoutInterval = 10.0f;
    
    
    @implementation HZNetworkConfig
    - (instancetype)init {
        self = [super init];
        if (self) {
            _timeoutInterval = HZRequestTimeoutInterval;
            _requestCachePolicy = HZRequestCacheAndLoadToCache;
            _resultCacheDuration = 7*24*60*60;
        }
        return self;
    }
    
    - (AFHTTPRequestSerializer *)requestSerializer {
        if (!_requestSerializer) {
            _requestSerializer = [AFHTTPRequestSerializer serializer];
            _requestSerializer.timeoutInterval = _timeoutInterval;
        }
        return _requestSerializer;
    }
    
    - (AFHTTPResponseSerializer *)responseSerializer {
        if (!_responseSerializer) {
            _responseSerializer = [AFJSONResponseSerializer serializer];
        }
        return _responseSerializer;
    }
    
    - (instancetype)copyWithZone:(NSZone *)zone {
        HZNetworkConfig *configuration = [[HZNetworkConfig alloc] init];
        configuration.resultCacheDuration = self.resultCacheDuration;
        configuration.requestCachePolicy = self.requestCachePolicy;
        configuration.baseURL = [self.baseURL copy];
        configuration.builtinHeaders = [self.builtinHeaders copy];
        configuration.builtinBodys = [self.builtinBodys copy];
        configuration.resposeHandle = [self.resposeHandle copy];
        configuration.requestSerializer = [AFHTTPRequestSerializer serializer];
        configuration.requestSerializer.timeoutInterval = self.requestSerializer.timeoutInterval;
    //    configuration.requestSerializer = [self.requestSerializer copy];
        configuration.responseSerializer = [self.responseSerializer copy];
        configuration.responseSerializer.acceptableContentTypes = self.responseSerializer.acceptableContentTypes;
        return configuration;
    }
    
    @end
    

    HZNetworkManager

    发起网络请求,单例

    /单例方法
    + (instancetype)sharedInstance{
       return [[self alloc] init];
    }
    
    - (instancetype)init {
       static dispatch_once_t onceToken;
       dispatch_once(&onceToken, ^{
           instance = [super init];
           if (self) {
               [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                   NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
                   instance.networkStatus = status;
               }];
               [[AFNetworkReachabilityManager sharedManager] startMonitoring];
               
               instance.configuration = [[HZNetworkConfig alloc] init];
               
               _methodMap = @{
                              @"0" : @"POST",
                              @"1" : @"GET",
                              @"2" : @"HEAD",
                              @"3" : @"PUT",
                              @"4" : @"DELETE",
                              };
               if (!_cacheKeys) {
                   _cacheKeys = [NSMutableDictionary dictionary];
               }
           }
       });
       return instance;
    }
    
    //alloc会调用allocWithZone,确保使用同一块内存地址
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
       static dispatch_once_t onceToken;
       dispatch_once(&onceToken, ^{
           instance = [super allocWithZone:zone];
       });
       return instance;
    }
    //copy的时候会调用copyWithZone
    - (id)copyWithZone:(NSZone *)zone{
       return instance;
    }
    + (id)copyWithZone:(struct _NSZone *)zone{
       return instance;
    }
    + (id)mutableCopyWithZone:(struct _NSZone *)zone{
       return instance;
    }
    - (id)mutableCopyWithZone:(NSZone *)zone{
       return instance;
    }
    #pragma mark - 实例化
    - (AFHTTPSessionManager *)requestManager {
       if (!_requestManager) {
           NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
           NSString *key = [userDefault objectForKey:HZNetworkManagerCharles];
           if ([key isEqualToString:@"1"]) {
               // debug 版本的包仍然能够正常抓包
               _requestManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.baidu.com"]];
           }else {//禁止抓包
               NSURLSessionConfiguration *conf = [NSURLSessionConfiguration ephemeralSessionConfiguration];
               conf.connectionProxyDictionary = @{};
               _requestManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.baidu.com"] sessionConfiguration:conf];
           }
           AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
           securityPolicy.allowInvalidCertificates = YES;
           securityPolicy.validatesDomainName = NO;
           _requestManager.securityPolicy = securityPolicy;
       }
       return _requestManager;
    }
    
    
    /**
     网络请求
    
     @param method 请求方法
     @param URLString 请求URL地址,不包含baseUrl
     @param parameters 请求参数
     @param configurationHandler 将默认的配置给到外面,外面可能需要特殊处理,可以修改baseUrl等信息
     @param cache  如果有的话返回缓存数据
     @param successed 请求成功
     @param failured 请求失败
     @return task
     */
    - (NSURLSessionDataTask *_Nullable)requestMethod:(HZRequestMethod)method
                                           URLString:(NSString *_Nullable)URLString
                                          parameters:(NSDictionary *_Nullable)parameters
                                configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler
                                               cache:(HZRequestManagerCache _Nullable )cache
                                             successed:(HZRequestManagerSuccess _Nullable )successed
                                             failured:(HZRequestManagerFailure _Nullable )failured {
        HZNetworkConfig *configuration = [self disposeConfiguration:configurationHandler];
        if (!URLString) {
            URLString = @"";
        }
        NSString *requestUrl = [NSString stringWithFormat:@"%@/%@", configuration.baseURL, URLString];
        parameters = [self disposeRequestParameters:parameters];
        
        //获取缓存数据
        id (^fetchCacheRespose)(void) = ^id (void) {
            id resposeObject = [HZNetWorkCache httpCacheForURL:requestUrl parameters:parameters cacheValidTime:configuration.resultCacheDuration];
            if (resposeObject) {
                return resposeObject;
            }
            return nil;
        };
        
        //判断数据的返回
        if (configuration.requestCachePolicy == HZRequestCacheDontLoad || configuration.requestCachePolicy == HZRequestCacheAndLoadToCache || configuration.requestCachePolicy == HZRequestCacheOrLoadToCache) {
            id resposeObject = fetchCacheRespose();
            cache(resposeObject, nil);
            
            if ((configuration.requestCachePolicy == HZRequestCacheOrLoadToCache ) && resposeObject) {
                return nil;
            }
            
            if (configuration.requestCachePolicy == HZRequestCacheDontLoad) {
                return nil;
            }
        }
        
        //存数据
        void (^ saveCacheRespose)(id responseObject) = ^(id responseObject) {
            if (configuration.resultCacheDuration > 0) {
                [HZNetWorkCache setHttpCache:responseObject URL:requestUrl parameters:parameters];
            }
        };
        
        //接口请求
        if (method > self.methodMap.count - 1) {
            method = self.methodMap.count - 1;
        }
        NSString *methodKey = [NSString stringWithFormat:@"%d", (int)method];
        NSURLRequest *request = [self.requestManager.requestSerializer requestWithMethod:self.methodMap[methodKey]
                                                                               URLString:requestUrl
                                                                              parameters:parameters
                                                                                   error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
           [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        });
        __weak typeof(self) weakself = self;
        
        __block NSURLSessionDataTask *dataTask = [self.requestManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            });
            if (error) {
                if (configuration.requestCachePolicy == HZRequestLoadToCache || ((configuration.requestCachePolicy == HZRequestCacheOrLoadToCache || configuration.requestCachePolicy == HZRequestCacheAndLoadToCache)&& fetchCacheRespose() == nil)) {//如果网络请求失败,则直接取缓存数据
                    id resposeObject = [HZNetWorkCache httpCacheForURL:requestUrl parameters:parameters];
                    resposeObject ? cache(resposeObject, error) : failured(dataTask, error, weakself.networkStatus);
                }else {
                    failured(dataTask, error, weakself.networkStatus);
                }
                
            }else {
                if (configuration.requestCachePolicy != HZRequestLoadDontCache) {
                    saveCacheRespose(responseObject);
                }
                if (configuration.resposeHandle) {
                    responseObject = configuration.resposeHandle(dataTask, responseObject);
                }
                successed(dataTask, responseObject);
            }
        }];
        [dataTask resume];
        return dataTask;
    }
    
    /**
     上传资源
     
     @param URLString URLString 请求的URL地址,不包含baseUrl
     @param parameters 请求参数
     @param block 将要上传的资源回调
     @param configurationHandler 将默认的配置给到外面,外面可能需要特殊处理,可以修改baseUrl等信息
     @param progress 上传资源进度
     @param successed 请求成功
     @param failured 请求失败
     @return task
     */
    - (NSURLSessionTask *_Nullable)uploadWithURLString:(NSString *_Nullable)URLString
                                            parameters:(NSDictionary *_Nullable)parameters
                             constructingBodyWithBlock:(void (^_Nullable)(id <AFMultipartFormData> _Nullable formData))block
                                  configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler
                                              progress:(HZRequestManagerProgress _Nullable)progress
                                               successed:(HZRequestManagerSuccess _Nullable )successed
                                               failured:(HZRequestManagerFailure _Nullable )failured {
        HZNetworkConfig *configuration = [self disposeConfiguration:configurationHandler];
        parameters = [self disposeRequestParameters:parameters];
        NSString *requestUrl = [NSString stringWithFormat:@"%@/%@", configuration.baseURL, URLString];
        __weak typeof(self) weakself = self;
        
        NSURLSessionDataTask *dataTask = [self.requestManager POST:requestUrl
                                                        parameters:parameters
                                         constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                                             block(formData);
                                         } progress:^(NSProgress * _Nonnull uploadProgress) {
                                             progress(uploadProgress);
                                         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                             successed(task, responseObject);
                                         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                             failured(task, error, weakself.networkStatus);
                                         }];
        [dataTask resume];
        return dataTask;
    }
    /** 取消所有的网络请求 */
    - (void)cancelAllRequest {
        [self.requestManager invalidateSessionCancelingTasks:YES];
    }
    
    #pragma mark - 内部方法
    - (NSDictionary *)disposeRequestParameters:(NSDictionary *)parameters {
        NSMutableDictionary *bodys = [NSMutableDictionary dictionaryWithDictionary:parameters];
        if (self.configuration.builtinBodys.allKeys.count > 0) {
            for (NSString *key in self.configuration.builtinBodys) {
                [bodys setObject:self.configuration.builtinBodys[key] forKey:key];
            }
        }
        return bodys;
    }
    
    - (HZNetworkConfig *)disposeConfiguration:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler {
        //configuration配置
        HZNetworkConfig *configuration = [self.configuration copy];
        if (configurationHandler) {
            configurationHandler(configuration);
        }
        self.requestManager.requestSerializer = configuration.requestSerializer;
        self.requestManager.responseSerializer = configuration.responseSerializer;
        if (configuration.builtinHeaders.allKeys.count > 0) {
            for (NSString *key in configuration.builtinHeaders) {
                [self.requestManager.requestSerializer setValue:configuration.builtinHeaders[key] forHTTPHeaderField:key];
            }
        }
        
        [self.requestManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        if (configuration.timeoutInterval > 0) {
            self.requestManager.requestSerializer.timeoutInterval = configuration.timeoutInterval;
        }else {
            self.requestManager.requestSerializer.timeoutInterval = HZRequestTimeoutInterval;
        }
        [self.requestManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        return configuration;
    }
    
    
    - (NSString *)serializeParams:(NSDictionary *)params {
        NSMutableArray *parts = [NSMutableArray array];
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id<NSObject> obj, BOOL *stop) {
            NSString *part = [NSString stringWithFormat: @"%@=%@", key, obj];
            [parts addObject: part];
        }];
        if (parts.count > 0) {
            NSString *queryString = [parts componentsJoinedByString:@"&"];
            return queryString ? [NSString stringWithFormat:@"?%@", queryString] : @"";
        }
        return @"";
    }
    
    @end
    

    使用

    @interface HZLitchNetWork : NSObject
    @property (nonatomic, strong) NSString * _Nullable baseURL;
    @property (nonatomic, assign) BOOL logOut;
    
    @property (nonatomic, copy) NSString *HostURL;
    @property (nonatomic, copy) NSString *HOSTURL;
    @property (nonatomic, copy) NSString *IMURL;
    
    + (instancetype)sharedInstance;
    
    - (NSURLSessionTask *_Nullable)POST:(NSString *)url parameters:(NSDictionary * _Nullable)parameters configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler cache:(HZRequestManagerCache _Nullable )cache successed:(HZRequestManagerSuccess _Nullable )successed failured:(HZRequestManagerFailure _Nullable )failured;
    
    /**
     上传图片资源
     
     @param url 连接
     @param parameters 参数
     @param block 文件
     @param configurationHandler e配置
     @param successed 成功回调
     @param failured 失败回调
     @return NSURLSessionTask
     */
    - (NSURLSessionTask *_Nullable)uploadWithURLString:(NSString *)url
                                            parameters:(NSDictionary * _Nullable)parameters
                             constructingBodyWithBlock:(void (^_Nullable)(id <AFMultipartFormData> _Nullable formData))block
                                  configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler
                                             successed:(HZRequestManagerSuccess _Nullable )successed
                                              failured:(HZRequestManagerFailure _Nullable )failured;
    
    @interface HZLitchNetWork()
    @property (nonatomic, strong) HZNetworkManager *requestManager;
    
    @end
    
    @implementation HZLitchNetWork
    static HZLitchNetWork *instance;
    //初始化方法
    - (instancetype)init{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [super init];
            instance.requestManager = [HZNetworkManager sharedInstance];
            [instance initialConfig];
        });
        return instance;
    }
    //单例方法
    + (instancetype)sharedInstance{
        return [[self alloc] init];
    }
    //alloc会调用allocWithZone,确保使用同一块内存地址
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [super allocWithZone:zone];
        });
        return instance;
    }
    //copy的时候会调用copyWithZone
    - (id)copyWithZone:(NSZone *)zone{
        return instance;
    }
    + (id)copyWithZone:(struct _NSZone *)zone{
        return instance;
    }
    + (id)mutableCopyWithZone:(struct _NSZone *)zone{
        return instance;
    }
    - (id)mutableCopyWithZone:(NSZone *)zone{
        return instance;
    }
    
    
    - (void)initialConfig {
        
        self.requestManager.configuration.baseURL = [self HOSTURL];
        //    self.requestConvertManager.configuration.resultCacheDuration = 1;
        self.requestManager.configuration.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
        //通过configuration来统一处理输出的数据,比如对token失效处理、对需要重新登录拦截
        self.requestManager.configuration.resposeHandle = ^id (NSURLSessionTask *dataTask, id responseObject) {
            if ([responseObject[@"errcode"] integerValue] == 40002) {
    
                [[NSNotificationCenter defaultCenter] postNotificationName:ConfigurationResposeHandle object:nil];
            }
            return responseObject;
        };
        
    }
    
    - (void)setBaseURL:(NSString *)baseURL {
        _baseURL = baseURL;
        self.requestManager.configuration.baseURL = baseURL;
    }
    
    
    #pragma mark - 缓存管理
    - (void)clearRequestCache:(NSString *_Nullable)urlString parameters:(NSDictionary *_Nullable)parameters {
        [HZNetWorkCache removeHttpCacheWithUrl:urlString parameters:parameters];
    }
    
    - (void)clearAllCache {
        [HZNetWorkCache removeAllHttpCache];
    }
    
    
    - (NSURLSessionTask *_Nullable)POST:(NSString *)url parameters:(NSDictionary * _Nullable)parameters configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler cache:(HZRequestManagerCache _Nullable )cache successed:(HZRequestManagerSuccess _Nullable )successed failured:(HZRequestManagerFailure _Nullable )failured {
        
        return [self.requestManager requestMethod:HZRequestMethodPost URLString:url parameters:parameters configurationHandler:^(HZNetworkConfig * _Nullable configuration) {
            NSString *contentStr = [[HeaderModel new] mj_JSONString];
            configuration.builtinHeaders = [NSMutableDictionary dictionary];
            [configuration.builtinHeaders setObject:contentStr forKey:@"App-Common-Params"];
            if (configurationHandler) {
                configurationHandler(configuration);
            }
        } cache:^(id  _Nullable responseObject, NSError *error) {
            cache ? cache(responseObject, error) : nil;
        } successed:^(NSURLSessionTask * _Nullable task, id  _Nullable responseObject) {
            successed ? successed(task, responseObject) : nil;
        } failured:^(NSURLSessionTask * _Nullable task, NSError * _Nullable error, AFNetworkReachabilityStatus netWorkStatus) {
            failured ? failured(task, error, netWorkStatus) : nil;
        }];
    }
    
    
    /**
     上传图片资源
    
     @param url 连接
     @param parameters 参数
     @param block 文件
     @param configurationHandler e配置
     @param successed 成功回调
     @param failured 失败回调
     @return NSURLSessionTask
     */
    - (NSURLSessionTask *_Nullable)uploadWithURLString:(NSString *)url
                                            parameters:(NSDictionary * _Nullable)parameters
                             constructingBodyWithBlock:(void (^_Nullable)(id <AFMultipartFormData> _Nullable formData))block
                                  configurationHandler:(void (^_Nullable)(HZNetworkConfig * _Nullable configuration))configurationHandler
                                             successed:(HZRequestManagerSuccess _Nullable )successed
                                              failured:(HZRequestManagerFailure _Nullable )failured {
        
        return [self.requestManager uploadWithURLString:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nullable formData) {
            block ? block(formData) : nil;
        } configurationHandler:^(HZNetworkConfig * _Nullable configuration) {
            NSString *contentStr = [[HeaderModel new] mj_JSONString];
            configuration.builtinHeaders = [NSMutableDictionary dictionary];
            [configuration.builtinHeaders setObject:contentStr forKey:@"App-Common-Params"];
            if (configurationHandler) {
                configurationHandler(configuration);
            }
            
        } progress:^(NSProgress * _Nullable progress) {
            
        } successed:^(NSURLSessionTask * _Nullable task, id  _Nullable responseObject) {
            successed ? successed(task, responseObject) : nil;
        } failured:^(NSURLSessionTask * _Nullable task, NSError * _Nullable error, AFNetworkReachabilityStatus netWorkStatus) {
            failured ? failured(task, error, netWorkStatus) : nil;
        }];
    }
    

    代码

    相关文章

      网友评论

          本文标题:利用YYCache和AFN实现网络数据缓存

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