iOS AFNetworking各种功能封装类代码
这个封装类包含了GET请求,POST请求,上传图片,上传多张图片,下载图片,判断网络是否可用等功能。
#import@interfaceHttpUtil:NSObject typedefNS_ENUM(NSInteger,NetworkReachabilityStatus){NetworkReachabilityStatusUnknown=-1,NetworkReachabilityStatusNotReachable=0,NetworkReachabilityStatusReachableViaWWAN=1,NetworkReachabilityStatusReachableViaWiFi=2, }; //GET请求 +(void)getWithURLString:(NSString*)URLString parameters:(id)parameters success:(void(^)(id))success failure:(void(^)(NSError*error))failure; //POST请求 +(void)postWithURLString:(NSString*)URLString parameters:(id)parameters success:(void(^)(id))success failure:(void(^)(NSError*))failure; //上传图片 +(void)uploadWithURLString:(NSString*)URLString parameters:(id)parameters uploadData:(NSData*)uploadData uploadName:(NSString*)uploadName success:(void(^)())success failure:(void(^)(NSError*))failure; //上传多张图片 +(void)uploadMostImageWithURLString:(NSString*)URLString parameters:(id)parameters uploadDatas:(NSArray*)uploadDatas uploadName:(NSString*)uploadName success:(void(^)())success failure:(void(^)(NSError*))failure; +(void)DownLoadWithUrlString:(NSString*)URLString parameters:(id)parameters progress:(void(^)(id))progress success:(void(^)(NSURL*filePath))success; +(void)setReachabilityStatusChangeBlock:(void(^)(NetworkReachabilityStatusstatus))block; +(void)stopMonitoring; +(Boolean)JudgeNetisConnect; @end
#import"HttpUtil.h" #import"AFNetworking.h" @implementationHttpUtil #pragmamark--GET请求-- +(void)getWithURLString:(NSString*)URLString parameters:(id)parameters success:(void(^)(id))success failure:(void(^)(NSError*error))failure{ AFHTTPSessionManager*manager=[AFHTTPSessionManagermanager]; manager.requestSerializer.timeoutInterval=10; manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil]; [managerGET:URLStringparameters:parametersprogress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject){ if(responseObject){ success(responseObject); } }failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror){ if(error){ failure(error); } }]; } #pragmamark--POST请求-- +(void)postWithURLString:(NSString*)URLString parameters:(id)parameters success:(void(^)(id))success failure:(void(^)(NSError*))failure{ AFHTTPSessionManager*manager=[AFHTTPSessionManagermanager]; //manager.requestSerializer.HTTPMethodsEncodingParametersInURI=[NSSetsetWithArray:@[@"POST",@"GET",@"HEAD"]]; manager.requestSerializer.timeoutInterval=10; manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil]; [managerPOST:URLStringparameters:parametersprogress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject){ if(success){ success(responseObject); } }failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror){ if(failure){ failure(error); } }]; } #pragmamark--上传图片-- +(void)uploadWithURLString:(NSString*)URLString parameters:(id)parameters uploadData:(NSData*)uploadData uploadName:(NSString*)uploadName success:(void(^)())success failure:(void(^)(NSError*))failure{ AFHTTPSessionManager*manager=[AFHTTPSessionManagermanager]; manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil]; [managerPOST:URLStringparameters:parametersconstructingBodyWithBlock:^(id_NonnullformData){ [formDataappendPartWithFileData:uploadDataname:uploadNamefileName:uploadNamemimeType:@"image/png"]; }progress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject){ if(success){ success(responseObject); } }failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror){ if(failure){ failure(error); } }]; } //上传多张图片uploadDatas图片的data集合 //uploadName文件名称最好以xxx1xxx2表示image1image2 +(void)uploadMostImageWithURLString:(NSString*)URLString parameters:(id)parameters uploadDatas:(NSArray*)uploadDatas uploadName:(NSString*)uploadName success:(void(^)())success failure:(void(^)(NSError*))failure{ AFHTTPSessionManager*manager=[AFHTTPSessionManagermanager]; manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html",nil]; [managerPOST:URLStringparameters:parametersconstructingBodyWithBlock:^(id _NonnullformData){ for(inti=0;uploadDatas.count;i++){ NSString*imageName=[NSStringstringWithFormat:@"%@[%i]",uploadName,i]; [formDataappendPartWithFileData:uploadDatas[i]name:uploadNamefileName:imageNamemimeType:@"image/png"]; } }progress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject){ if(success){ success(responseObject); } }failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror){ if(failure){ failure(error); } }]; } +(void)DownLoadWithUrlString:(NSString*)URLString parameters:(id)parameters progress:(void(^)(id))progress success:(void(^)(NSURL*filePath))success { //1.创建管理者对象 AFHTTPSessionManager*manager=[AFHTTPSessionManagermanager]; URLString=[selfDownLoadUrlWithParams:URLStringWithNSDictionaryParams:parameters]; NSLog(@"DownLoadFileUrl%@",URLString); NSURL*url=[NSURLURLWithString:URLString]; //3.创建请求对象 NSURLRequest*request=[NSURLRequestrequestWithURL:url]; //下载任务 NSURLSessionDownloadTask*task=[managerdownloadTaskWithRequest:requestprogress:^(NSProgress*_NonnulldownloadProgress){ if(progress){ progress(downloadProgress); } }destination:^NSURL*_Nonnull(NSURL*_NonnulltargetPath,NSURLResponse*_Nonnullresponse){ ////下载地址 ////设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象 NSString*filePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]; filePath=[filePathstringByAppendingPathComponent:@"DFU.zip"]; return[NSURLfileURLWithPath:filePath]; }completionHandler:^(NSURLResponse*_Nonnullresponse,NSURL*_NullablefilePath,NSError*_Nullableerror){ if(success){ success(filePath); } }]; //开始启动任务 [taskresume]; } //因为下载的方法不能够直接填写dict参数进去,所以只有使用这种方法拼接参数进去 +(NSString*)DownLoadUrlWithParams:(NSString*)urlWithNSDictionaryParams:(NSDictionary*)params{ //初始化参数变量 NSString*body=@""; //快速遍历参数数组 NSString*appendUrl; for(idkeyinparams){ NSLog(@"key:%@value:%@",key,[paramsobjectForKey:key]); body=[bodystringByAppendingString:key]; body=[bodystringByAppendingString:@"="]; body=[bodystringByAppendingString:[paramsobjectForKey:key]]; body=[bodystringByAppendingString:@"&"]; } //处理多余的&以及返回含参url if(body.length>1){ //去掉末尾的& body=[bodysubstringToIndex:body.length-1]; //返回含参url } appendUrl=[urlstringByAppendingString:body]; returnappendUrl; } +(void)setReachabilityStatusChangeBlock:(void(^)(NetworkReachabilityStatusstatus))block{//监测网络状态 AFNetworkReachabilityManager*netMan=[AFNetworkReachabilityManagersharedManager]; [netMansetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus){ switch(status){ //未知网络 caseAFNetworkReachabilityStatusUnknown: if(block){ block(NetworkReachabilityStatusUnknown); } break; //没有网络 caseAFNetworkReachabilityStatusNotReachable: if(block){ block(NetworkReachabilityStatusNotReachable); } break; //手机自带网络 caseAFNetworkReachabilityStatusReachableViaWWAN: if(block){ block(NetworkReachabilityStatusReachableViaWWAN);} break; //WIFI caseAFNetworkReachabilityStatusReachableViaWiFi: if(block){ block(NetworkReachabilityStatusReachableViaWiFi);} break; } }]; [netManstartMonitoring];} +(void)stopMonitoring{ AFNetworkReachabilityManager*netMan=[AFNetworkReachabilityManagersharedManager]; [netManstopMonitoring]; } +(Boolean)JudgeNetisConnect{ NSString*urlstr=WuCheBaseUrl; NSURLRequest*request=[NSURLRequestrequestWithURL:[NSURLURLWithString:urlstr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0]; NSData*response=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil]; if(response!=NULL){ returnYES; } returnNO; } @end
以上这篇iOSAFNetworking各种功能封装类代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。