//
NetworkManager.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, NetworkStatus) {
/** 未知网络*/
NetworkStatusUnknown,
/** 无网络*/
NetworkStatusNotReachable,
/** 手机网络*/
NetworkStatusReachableViaWWAN,
/** WIFI网络*/
NetworkStatusReachableViaWiFi
};
/** 请求成功的Block */
typedef void(^RequestSuccess)(id responseObject);
/** 请求失败的Block */
typedef void(^RequestFailed)(NSError *error);
/** 缓存的Block */
typedef void(^RequestCache)(id responseCache);
/** 网络状态的Block*/
typedef void(^GetNetworkStatus)(NetworkStatus status);
/** 上传或下载进度*/
typedef void(^HttpProgress)(NSProgress *progress);
@interface NetworkManager : NSObject
/**
* 开始监听网络状态
*/
+ (void)startGetNetworkStatus;
/**
* 实时获取网络状态回调
*/
+ (void)networkStatusWithBlock:(GetNetworkStatus)status;
/**
不带缓存的GET请求
@param urlStr 请求路径
@param success 请求成功
@param failure 请求失败
*/
+(void)startRequestGetWithurl:(NSString *)urlStr whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure;
/**
不带缓存的POST请求
@param urlStr 请求路径
@param params 请求参数
@param success 请求成功
@param failure 请求失败
*/
+(void)startRequestWithurl:(NSString *)urlStr andParams:(NSDictionary *)params whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure;
/**
带缓存的GET请求
@param urlStr 请求路径
@param requestCache 原来的缓存
@param success 请求成功
@param failure 请求失败
*/
+(void)startRequestGetWithurl:(NSString *)urlStr andRequestCache:(RequestCache)requestCache whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure;
/**
带缓存的POST请求
@param urlStr 请求路径
@param requestCache 原来的缓存
@param params 请求参数
@param success 请求成功
@param failure 请求失败
*/
+(void)startRequestWithurl:(NSString *)urlStr andRequestCache:(RequestCache)requestCache andParams:(NSDictionary *)params whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure;
/**
上传单张图片
@param urlStr 上传路径
@param parm 上传参数
@param image 上传的图片
@param success 上传成功
@param failure 上传失败
*/
+(void)uploadImageWithUrl:(NSString *)urlStr andParm:(NSDictionary *)parm andImage:(UIImage *)image andWhenSuccess:(RequestSuccess)success andWhenFailure:(RequestFailed)failure;
/**
上传多张图片
@param urlStr 上传路径
@param parm 上传参数
@param imageArr 上传的图片
@param progress 上传的进度
@param success 上传成功
@param failure 上传失败
*/
+(void)uploadImageArrayWithUrl:(NSString *)urlStr andParm:(NSDictionary *)parm andImage:(NSArray <UIImage *> *)imageArr andProgress:(HttpProgress)progress andWhenSuccess:(RequestSuccess)success andWhenFailure:(RequestFailed)failure;
/**
下载文件
@param URL 下载路径
@param fileDir 保存路径
@param progress 下载进度
@param success 下载成功
@param failure 下载失败
@return 下载任务
*/
+ (NSURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(HttpProgress)progress success:(void(^)(NSString *))success failure:(RequestFailed)failure;
/**
获取缓存大小
@return 缓存大小的字符串
*/
+(NSString *)getCacheSize;
/**
移除所有缓存
*/
+(void)removeAllCache;
@end
/
NetworkManager.m
#import "NetworkManager.h"
#import "AFNetworking.h"
#import <YYCache.h>
#import "SDImageCache.h"
@implementation NetworkManager
static AFHTTPSessionManager *_sessionManager = nil;
static GetNetworkStatus _networkStatus;
static NSString *const _NetworkResponseCache = @"NetworkRequestCache";
static YYCache *_dataCache;
/**
开始监听网络状态
*/
+(void)startGetNetworkStatus{
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status)
{
case AFNetworkReachabilityStatusUnknown:
_networkStatus(NetworkStatusUnknown);
break;
case AFNetworkReachabilityStatusNotReachable:
_networkStatus(NetworkStatusNotReachable);
break;
//手机自带网络
case AFNetworkReachabilityStatusReachableViaWWAN:
_networkStatus(NetworkStatusReachableViaWWAN);
break;
//Wifi
case AFNetworkReachabilityStatusReachableViaWiFi:
_networkStatus(NetworkStatusReachableViaWiFi);
break;
}
}];
[manager startMonitoring];
}
/**
获取网络状态
@param status 获取网络状态的Block
*/
+(void)networkStatusWithBlock:(GetNetworkStatus)status{
_networkStatus = status;
}
//****************************不带缓存的GET和POST请求
//使用GET方法获取数据
+(void)startRequestGetWithurl:(NSString *)urlStr whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure{
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
[manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
//使用POST方法获取数据
+(void)startRequestWithurl:(NSString *)urlStr andParams:(NSDictionary *)params whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure{
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
[manager POST:urlStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
//**************************带缓存GET和POST请求
//使用GET方法获取数据
+(void)startRequestGetWithurl:(NSString *)urlStr andRequestCache:(RequestCache)requestCache whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure{
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
if (requestCache) {
requestCache([self getResponseCacheForKey:urlStr]);
}
[manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
[self saveResponseCache:responseObject forKey:urlStr];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
//使用POST方法获取数据
+(void)startRequestWithurl:(NSString *)urlStr andRequestCache:(RequestCache)requestCache andParams:(NSDictionary *)params whenSuccess:(RequestSuccess)success andFailure:(RequestFailed)failure{
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
if (requestCache) {
requestCache([self getResponseCacheForKey:urlStr]);
}
[manager POST:urlStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
[self saveResponseCache:responseObject forKey:urlStr];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
//上传单张图片
+(void)uploadImageWithUrl:(NSString *)urlStr andParm:(NSDictionary *)parm andImage:(UIImage *)image andWhenSuccess:(RequestSuccess)success andWhenFailure:(RequestFailed)failure{
NSData *imageData = UIImagePNGRepresentation(image);
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
// 给图片重命名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
[manager POST:urlStr parameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 上传文件
[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if (success) {
success(dic);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
//上传多张图片
+(void)uploadImageArrayWithUrl:(NSString *)urlStr andParm:(NSDictionary *)parm andImage:(NSArray <UIImage *> *)imageArr andProgress:(HttpProgress)progress andWhenSuccess:(RequestSuccess)success andWhenFailure:(RequestFailed)failure{
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
[manager POST:urlStr parameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//压缩-添加-上传图片
[imageArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
[formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%@%ld.png",fileName,idx] mimeType:@"image/png"];
}];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//上传进度
if (progress) {
progress(uploadProgress);
}
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (failure) {
failure(error);
}
}];
}
//下载文件
+ (NSURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(HttpProgress)progress success:(void(^)(NSString *))success failure:(RequestFailed)failure
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPSessionManager *manager = [self createAFHTTPSessionManager];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//下载进度
if (progress) {
progress(downloadProgress);
// NSLog(@"下载进度:%.2f%%",100.0*downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
}
} 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) {
//下载成功返回下载路径
success ? success(filePath.absoluteString) : nil;
failure && error ? failure(error) : nil;
}];
//开始下载
[downloadTask resume];
return downloadTask;
}
//缓存操作 在程序运行过程中,它会在你程序中每个类调用一次initialize 初始化 _dataCache
+ (void)initialize
{
_dataCache = [YYCache cacheWithName:_NetworkResponseCache];
[_dataCache.memoryCache setCountLimit:50];//内存最大缓存数据个数
[_dataCache.memoryCache setCostLimit:1*1024];//内存最大缓存开销 目前这个毫无用处
[_dataCache.diskCache setCostLimit:10*1024];//磁盘最大缓存开销
[_dataCache.diskCache setCountLimit:50];//磁盘最大缓存数据个数
[_dataCache.diskCache setAutoTrimInterval:60];//设置磁盘lru动态清理频率 默认 60秒
}
+ (void)saveResponseCache:(id)responseCache forKey:(NSString *)key
{
//异步缓存,不会阻塞主线程
[_dataCache setObject:responseCache forKey:key withBlock:nil];
}
+ (id)getResponseCacheForKey:(NSString *)key
{
//NSLog(@"磁盘缓存位置%@",_dataCache.diskCache.path);
return [_dataCache objectForKey:key];
}
+(NSString *)getCacheSize{
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
NSInteger totalSize = _dataCache.memoryCache.totalCost + _dataCache.diskCache.totalCost + imageCacheSize;
NSString *totalSizeStr;
if (totalSize < 1024) {
totalSizeStr = [NSString stringWithFormat:@"%ldB",totalSize];
}else if (totalSize>=1024&&totalSize<1024*1024){
totalSizeStr = [NSString stringWithFormat:@"%.2fKB",totalSize/1024.0];
}else if(totalSize > 1024*1024) {
totalSizeStr = [NSString stringWithFormat:@"%.2fMB",totalSize/(1024.0*1024)];
}
return totalSizeStr;
}
+(void)removeAllCache{
[[SDImageCache sharedImageCache] clearDisk];
[_dataCache.diskCache removeAllObjects];
[_dataCache.memoryCache removeAllObjects];
}
#pragma mark - 设置AFHTTPSessionManager相关属性
+ (AFHTTPSessionManager *)createAFHTTPSessionManager
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//设置请求参数的类型:HTTP (AFJSONRequestSerializer,AFHTTPRequestSerializer)
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//设置请求的超时时间
manager.requestSerializer.timeoutInterval = 30.f;
//设置服务器返回结果的类型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer)
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
return manager;
}
@end