//
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 = [selfcreateAFHTTPSessionManager];
// 给图片重命名
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatterstringFromDate:[NSDatedate]];
NSString *fileName = [NSStringstringWithFormat:@"%@.png", str];
[manager POST:urlStrparameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 上传文件
[formData appendPartWithFileData:imageDataname:@"file"fileName:fileName mimeType:@"image/png"];
} progress:^(NSProgress *_Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:responseObjectoptions:NSJSONReadingMutableContainerserror: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 = [selfcreateAFHTTPSessionManager];
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatterstringFromDate:[NSDatedate]];
NSString *fileName = [NSStringstringWithFormat:@"%@.png", str];
[manager POST:urlStrparameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//压缩-添加-上传图片
[imageArr enumerateObjectsUsingBlock:^(UIImage *_Nonnull image, NSUInteger idx,BOOL * _Nonnull stop) {
NSData *imageData =UIImageJPEGRepresentation(image, 0.5);
[formData appendPartWithFileData:imageDataname:@"file"fileName:[NSStringstringWithFormat:@"%@%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) {
[UIapplicationsharedApplication].networkActivityIndicatorVisible =NO;
if (failure) {
failure(error);
}
}];
}
//下载文件
+ (NSURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(HttpProgress)progress success:(void(^)(NSString *))success failure:(RequestFailed)failure
{
[UIApplicationsharedApplication].networkActivityIndicatorVisible =YES;
AFHTTPSessionManager *manager = [selfcreateAFHTTPSessionManager];
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:URL]];
NSURLSessionDownloadTask *downloadTask = [managerdownloadTaskWithRequest: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 = [NSFileManagerdefaultManager];
//创建Download目录
[fileManager createDirectoryAtPath:downloadDirwithIntermediateDirectories:YESattributes:nilerror:nil];
//拼接文件路径
NSString *filePath = [downloadDirstringByAppendingPathComponent:response.suggestedFilename];
//返回文件位置的URL路径
return [NSURLfileURLWithPath: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 = [YYCachecacheWithName:_NetworkResponseCache];
[_dataCache.memoryCachesetCountLimit:50];//内存最大缓存数据个数
[_dataCache.memoryCachesetCostLimit:1*1024];//内存最大缓存开销目前这个毫无用处
[_dataCache.diskCachesetCostLimit:10*1024];//磁盘最大缓存开销
[_dataCache.diskCachesetCountLimit:50];//磁盘最大缓存数据个数
[_dataCache.diskCachesetAutoTrimInterval:60];//设置磁盘lru动态清理频率默认 60秒
}
+ (void)saveResponseCache:(id)responseCache forKey:(NSString *)key
{
//异步缓存,不会阻塞主线程
[_dataCachesetObject:responseCache forKey:keywithBlock:nil];
}
+ (id)getResponseCacheForKey:(NSString *)key
{
//NSLog(@"磁盘缓存位置%@",_dataCache.diskCache.path);
return [_dataCacheobjectForKey:key];
}
+(NSString *)getCacheSize{
NSUInteger imageCacheSize = [[SDImageCachesharedImageCache] getSize];
NSInteger totalSize =_dataCache.memoryCache.totalCost +_dataCache.diskCache.totalCost + imageCacheSize;
NSString *totalSizeStr;
if (totalSize < 1024) {
totalSizeStr = [NSStringstringWithFormat:@"%ldB",totalSize];
}elseif (totalSize>=1024&&totalSize<1024*1024){
totalSizeStr = [NSStringstringWithFormat:@"%.2fKB",totalSize/1024.0];
}elseif(totalSize > 1024*1024) {
totalSizeStr = [NSStringstringWithFormat:@"%.2fMB",totalSize/(1024.0*1024)];
}
return totalSizeStr;
}
+(void)removeAllCache{
[[SDImageCachesharedImageCache] clearDisk];
[_dataCache.diskCacheremoveAllObjects];
[_dataCache.memoryCacheremoveAllObjects];
}
#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
新闻热点
疑难解答