美文网首页
OC:封装网络请求

OC:封装网络请求

作者: 春暖花已开 | 来源:发表于2019-01-24 10:59 被阅读59次

Mock:https://www.mocky.io/

MZNetwork.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, MZNetworkStatusType) {
    MZNetworkStatusTypeUnknown          = -1,
    MZNetworkStatusTypeNotReachable     = 0,
    MZNetworkStatusTypeWWAN = 1,
    MZNetworkStatusTypeWiFi = 2,
};

typedef NS_ENUM(NSUInteger, MZRequestSerializer) {
    /// 设置请求数据为JSON格式
    MZRequestSerializerJSON,
    /// 设置请求数据为二进制格式
    MZRequestSerializerHTTP,
};

typedef NS_ENUM(NSUInteger, MZResponseSerializer) {
    /// 设置响应数据为JSON格式
    MZResponseSerializerJSON,
    /// 设置响应数据为二进制格式
    MZResponseSerializerHTTP,
};


/** 成功 */
typedef void(^MZHttpRequestSuccess) (id responseObject);
/** 失败 */
typedef void(^MZHttpRequestFailed) (NSError *error);
/** 上传或下载进度,completedUnitCount:当前大小;totalUnitCount:总大小 */
typedef void(^MZHttpProgress)(NSProgress *progress);
/** 网络状态的回调 */
typedef void (^MZNetworkStatusBlock)(MZNetworkStatusType type);
/** 缓存的Block */
typedef void(^MZHttpRequestCache)(id responseCache);


@class AFHTTPSessionManager;
@interface MZNetwork : NSObject

/** 有网YES, 无网:NO */
+ (BOOL)isNetwork;

/** 手机网络:YES, 反之:NO */
+ (BOOL)isWWANNetwork;

/** WiFi网络:YES, 反之:NO */
+ (BOOL)isWiFiNetwork;

/** 取消所有HTTP请求 */
+ (void)cancelAllRequests;

/** 实时获取网络状态,通过Block回调实时获取(此方法可多次调用) */
+ (void)networkStatusWithBlock:(MZNetworkStatusBlock)networkStatus;

/** 取消指定URL的HTTP请求 */
+ (void)cancelRequestWithURL:(NSString *)URL;

/** 开启日志打印 (Debug级别) */
+ (void)openLog;

/** 关闭日志打印,默认关闭 */
+ (void)closeLog;


/**
 *  GET请求,无缓存
 */
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL parameters:(id)parameters success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  GET请求,自动缓存
 */
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL parameters:(id)parameters responseCache:(MZHttpRequestCache)responseCache success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  POST请求,无缓存
 */
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL parameters:(id)parameters success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  POST请求,自动缓存
 */
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL parameters:(id)parameters responseCache:(MZHttpRequestCache)responseCache success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  上传文件
 */
+ (__kindof NSURLSessionTask *)uploadFileWithURL:(NSString *)URL parameters:(id)parameters name:(NSString *)name filePath:(NSString *)filePath progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  上传单/多张图片
 */
+ (__kindof NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL parameters:(id)parameters name:(NSString *)name images:(NSArray<UIImage *> *)images fileNames:(NSArray<NSString *> *)fileNames imageScale:(CGFloat)imageScale imageType:(NSString *)imageType progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

/**
 *  下载文件
 */
+ (__kindof NSURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(MZHttpProgress)progress success:(void(^)(NSString *filePath))success failure:(MZHttpRequestFailed)failure;



#pragma mark - 设置AFHTTPSessionManager相关属性
#pragma mark 注意: 因为全局只有一个AFHTTPSessionManager实例,所以以下设置方式全局生效
/** 在开发中,如果以下的设置方式不满足项目的需求,就调用此方法获取AFHTTPSessionManager实例进行自定义设置 */
+ (void)setAFHTTPSessionManagerProperty:(void(^)(AFHTTPSessionManager *sessionManager))sessionManager;

/** 设置网络请求参数的格式:默认为二进制格式 */
+ (void)setRequestSerializer:(MZRequestSerializer)requestSerializer;

/** 设置服务器响应数据格式:默认为JSON格式 */
+ (void)setResponseSerializer:(MZResponseSerializer)responseSerializer;

/** 设置请求超时时间:默认为15S */
+ (void)setRequestTimeoutInterval:(NSTimeInterval)time;

/** 设置请求头 */
+ (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

/** 是否打开网络状态转圈菊花:默认打开 */
+ (void)openNetworkActivityIndicator:(BOOL)open;

/**
 配置自建证书的Https请求
 */
+ (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName;


/**
 上传图片
 */
+ (void)POST:(NSString *)URL parameters:(NSDictionary *)params image:(UIImage *)image name:(NSString *)name progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure;

@end
MZNetwork.m
#import "MZNetwork.h"

#import "MZNetworkCache.h"

//Libs
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"

#ifdef DEBUG
#define MZKitLog(format, ...) printf("class: <%p %s:(%d) > method: %s \n%s\n", self, [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, __PRETTY_FUNCTION__, [[NSString stringWithFormat:(format), ##__VA_ARGS__] UTF8String] )
#else
#define MZKitLog(...)
#endif

static BOOL _isOpenLog;   // 是否已开启日志打印
static NSMutableArray *_allSessionTask;
static AFHTTPSessionManager *_sessionManager;

@implementation MZNetwork

/** 有网YES, 无网:NO */
+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].isReachable;
}

/** 手机网络:YES, 反之:NO */
+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}

/** WiFi网络:YES, 反之:NO */
+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}

/** 实时获取网络状态,通过Block回调实时获取(此方法可多次调用) */
+ (void)networkStatusWithBlock:(MZNetworkStatusBlock)networkStatus {
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: {
                !networkStatus ?: networkStatus(MZNetworkStatusTypeUnknown);
                if (_isOpenLog) MZKitLog(@"未知网络");
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                !networkStatus ?: networkStatus(MZNetworkStatusTypeWWAN);
                if (_isOpenLog) MZKitLog(@"手机网络");
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: {
                !networkStatus ?: networkStatus(MZNetworkStatusTypeWiFi);
                if (_isOpenLog) MZKitLog(@"WiFi网络");
            }
                break;
                
            case AFNetworkReachabilityStatusNotReachable: {
                !networkStatus ?: networkStatus(MZNetworkStatusTypeNotReachable);
                if (_isOpenLog) MZKitLog(@"无网络");
            }
                break;
                
            default:
                break;
        }
    }];
}

/** 取消所有HTTP请求 */
+ (void)cancelAllRequests {
    
    // 锁操作
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

/** 取消指定URL的HTTP请求 */
+ (void)cancelRequestWithURL:(NSString *)URL {
    
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}

/** 开启日志打印 (Debug级别) */
+ (void)openLog {
    _isOpenLog = YES;
}

/** 关闭日志打印,默认关闭 */
+ (void)closeLog {
    _isOpenLog = NO;
}


/** 存储着所有的请求task数组 */
+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [NSMutableArray array];
    }
    return _allSessionTask;
}


#pragma mark - 初始化AFHTTPSessionManager相关属性
/** 开始监测网络状态 */
+ (void)load {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

/** 所有的HTTP请求共享一个AFHTTPSessionManager */
+ (void)initialize {
    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.requestSerializer.timeoutInterval = 15.f;
    _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}


#pragma mark - 网络请求

/** GET请求,无缓存 */
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL parameters:(id)parameters success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    return [self GET:URL parameters:parameters responseCache:nil success:success failure:failure];
}

/** GET请求,自动缓存 */
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL parameters:(id)parameters responseCache:(MZHttpRequestCache)responseCache success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    // 读取缓存
    !responseCache ?: responseCache([MZNetworkCache httpCacheForURL:URL parameters:parameters]);
    
    NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) { MZKitLog(@"%@", responseObject); };
        [[self allSessionTask] removeObject:task];
        !success ?: success(responseObject);
        // 对数据进行异步缓存
        responseCache != nil ? [MZNetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) { MZKitLog(@"error = %@",error); }
        [[self allSessionTask] removeObject:task];
        !failure ?: failure(error);
        
    }];
    
    // 添加sessionTask到数组
    !sessionTask ?: [[self allSessionTask] addObject:sessionTask];
    
    return sessionTask;
}

/** POST请求,无缓存 */
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL parameters:(id)parameters success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    return [self POST:URL parameters:parameters responseCache:nil success:success failure:failure];
}

/** POST请求,自动缓存 */
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL parameters:(id)parameters responseCache:(MZHttpRequestCache)responseCache success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    // 读取缓存
    !responseCache ?: responseCache([MZNetworkCache httpCacheForURL:URL parameters:parameters]);
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) { MZKitLog(@"%@", responseObject); };
        [[self allSessionTask] removeObject:task];
        !success ?: success(responseObject);
        // 对数据进行异步缓存
        responseCache != nil ? [MZNetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) { MZKitLog(@"error = %@",error); }
        [[self allSessionTask] removeObject:task];
        !failure ?: failure(error);
        
    }];
    
    // 添加sessionTask到数组
    !sessionTask ?: [[self allSessionTask] addObject:sessionTask];
    
    return sessionTask;
}

/** 上传文件 */
+ (__kindof NSURLSessionTask *)uploadFileWithURL:(NSString *)URL parameters:(id)parameters name:(NSString *)name filePath:(NSString *)filePath progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error = nil;
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error];
        (failure && error) ? failure(error) : nil;
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            !progress ?: progress(uploadProgress);
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) { MZKitLog(@"responseObject = %@",responseObject);}
        [[self allSessionTask] removeObject:task];
        !success ?: success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) { MZKitLog(@"error = %@",error);}
        [[self allSessionTask] removeObject:task];
        !failure ?: failure(error);
    }];
    
    // 添加sessionTask到数组
    !sessionTask ?: [[self allSessionTask] addObject:sessionTask];
    
    return sessionTask;
}

/** 上传单/多张图片 */
+ (__kindof NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL parameters:(id)parameters name:(NSString *)name images:(NSArray<UIImage *> *)images fileNames:(NSArray<NSString *> *)fileNames imageScale:(CGFloat)imageScale imageType:(NSString *)imageType progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSUInteger i = 0; i < images.count; i++) {
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
            // 默认图片的文件名, 若fileNames为nil就使用
            
            NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@", [[NSUUID UUID] UUIDString],(long)i,imageType?:@"jpg"];
            
            [formData appendPartWithFileData:imageData
                                        name:name
                                    fileName:fileNames ? [NSString stringWithFormat:@"%@.%@",fileNames[i],imageType?:@"jpg"] : imageFileName
                                    mimeType:[NSString stringWithFormat:@"image/%@",imageType ?: @"jpg"]];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            !progress ?: progress(uploadProgress);
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (_isOpenLog) { MZKitLog(@"responseObject = %@",responseObject);}
        [[self allSessionTask] removeObject:task];
        !success ?: success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_isOpenLog) { MZKitLog(@"error = %@",error);}
        [[self allSessionTask] removeObject:task];
        !failure ?: failure(error);
    }];
    
    // 添加sessionTask到数组
    !sessionTask ?: [[self allSessionTask] addObject:sessionTask];
    
    return sessionTask;
}

/** 下载文件 */
+ (__kindof NSURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(MZHttpProgress)progress success:(void(^)(NSString *filePath))success failure:(MZHttpRequestFailed)failure {
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
    __block NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //下载进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            !progress ?: progress(downloadProgress);
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //拼接缓存目录
        NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileDir ? fileDir : @"Download"];
        //打开文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //创建Download目录
        [fileManager createDirectoryAtPath:downloadDir withIntermediateDirectories:YES attributes:nil error:nil];
        //拼接文件路径
        NSString *filePath = [downloadDir stringByAppendingPathComponent:response.suggestedFilename];
        //返回文件位置的URL路径
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        [[self allSessionTask] removeObject:downloadTask];
        if(failure && error) {failure(error) ; return ;};
        /** NSURL->NSString*/
        !success ?: success(filePath.absoluteString);
        
    }];
    //开始下载
    [downloadTask resume];
    // 添加sessionTask到数组
    !downloadTask ?: [[self allSessionTask] addObject:downloadTask];
    
    return downloadTask;
}



#pragma mark - 设置AFHTTPSessionManager相关属性
#pragma mark 注意: 因为全局只有一个AFHTTPSessionManager实例,所以以下设置方式全局生效
/** 在开发中,如果以下的设置方式不满足项目的需求,就调用此方法获取AFHTTPSessionManager实例进行自定义设置 */
+ (void)setAFHTTPSessionManagerProperty:(void(^)(AFHTTPSessionManager *sessionManager))sessionManager {
    !sessionManager ?: sessionManager(_sessionManager);
}

/** 设置网络请求参数的格式:默认为二进制格式 */
+ (void)setRequestSerializer:(MZRequestSerializer)requestSerializer {
    _sessionManager.requestSerializer = requestSerializer == MZRequestSerializerHTTP ? [AFHTTPRequestSerializer serializer] : [AFJSONRequestSerializer serializer];
}

/** 设置服务器响应数据格式:默认为JSON格式 */
+ (void)setResponseSerializer:(MZResponseSerializer)responseSerializer {
    _sessionManager.responseSerializer = responseSerializer == MZResponseSerializerHTTP ? [AFHTTPResponseSerializer serializer] : [AFJSONResponseSerializer serializer];
}

/** 设置请求超时时间:默认为15S */
+ (void)setRequestTimeoutInterval:(NSTimeInterval)time {
    _sessionManager.requestSerializer.timeoutInterval = time;
}

/** 设置请求头 */
+ (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
    [_sessionManager.requestSerializer setValue:value forHTTPHeaderField:field];
}

/** 是否打开网络状态转圈菊花:默认打开 */
+ (void)openNetworkActivityIndicator:(BOOL)open {
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:open];
}

/** 配置自建证书的Https请求 */
+ (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName {
    
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    // 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // 如果需要验证自建证书(无效证书),需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    // 是否需要验证域名,默认为YES;
    securityPolicy.validatesDomainName = validatesDomainName;
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
    
    [_sessionManager setSecurityPolicy:securityPolicy];
}


#pragma mark - 以下为兼容"Version1.0.5"以下版本

/**
 *  上传图片
 */
+ (void)POST:(NSString *)URL parameters:(NSDictionary *)params image:(UIImage *)image name:(NSString *)name progress:(MZHttpProgress)progress success:(MZHttpRequestSuccess)success failure:(MZHttpRequestFailed)failure {
    
    [_sessionManager POST:URL parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);//进行图片压缩
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png", [[NSUUID UUID] UUIDString]];
        // 任意的二进制数据MIMEType application/octet-stream
        // name是服务器接收文件定义的字段, filename是上传的文件名称
        [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
}

@end
MZNetworkCache.h
#import <Foundation/Foundation.h>

@interface MZNetworkCache : NSObject

/**
 *  异步缓存网络数据,根据请求的 URL与parameters
 *  做KEY存储数据, 这样就能缓存多级页面的数据
 *
 *  @param httpData   服务器返回的数据
 *  @param URL        请求的URL地址
 *  @param parameters 请求的参数
 */
+ (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(id)parameters;

/**
 *  根据请求的 URL与parameters 同步取出缓存数据
 *
 *  @param URL        请求的URL
 *  @param parameters 请求的参数
 *
 *  @return 缓存的服务器数据
 */
+ (id)httpCacheForURL:(NSString *)URL parameters:(id)parameters;

/** 获取网络缓存的总大小 bytes(字节) */
+ (NSInteger)getAllHttpCacheSize;


/** 删除所有网络缓存 */ 
+ (void)removeAllHttpCache;

@end
MZNetworkCache.m
#import "MZNetworkCache.h"

#import "YYCache.h"

static NSString *const kMZNetworkResponseCache = @"kMZNetworkResponseCache";
static YYCache *_dataCache;

@implementation MZNetworkCache

+ (void)initialize {
    _dataCache = [YYCache cacheWithName:kMZNetworkResponseCache];
}

+ (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    //异步缓存,不会阻塞主线程
    [_dataCache setObject:httpData forKey:cacheKey withBlock:nil];
}

+ (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    return [_dataCache objectForKey:cacheKey];
}

+ (NSInteger)getAllHttpCacheSize {
    return [_dataCache.diskCache totalCost];
}

+ (void)removeAllHttpCache {
    [_dataCache.diskCache removeAllObjects];
}

+ (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];
    return [NSString stringWithFormat:@"%@%@",URL,paraString];
}

@end

相关文章

网友评论

      本文标题:OC:封装网络请求

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