博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AF3.1.0简单二次封装
阅读量:6425 次
发布时间:2019-06-23

本文共 8370 字,大约阅读时间需要 27 分钟。

hot3.png

#import 
@class AFNetworking;@interface ZJLAFRequest : NSObject+ (ZJLAFRequest *) sharedInstance;/** get请求*/- (void)GET:(NSString *)URLString dict:(id)dict progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^) (id responseObject))succeed failure:(void (^) (NSError *error))failure;/** post请求*/- (void)POST:(NSString *)URLString dict:(id)dict progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^)(id responseObject))succeed failure:(void (^)(NSError *error))failure;/** 下载文件*/-(void)DOWNLOAD:(NSString *)URLString progressFloat:(void (^)(float progressFloat))progressFloat downLoadDic:(void (^)(id responseObject))downLoadDic;/** 上传多张图片*/-(void)UPLOAD:(NSString *)URLString dict:(id)dict imageArray:(id)imageArray progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^) (id responseObject))succeed failure:(void (^) (NSError *error))failure;@end#import "ZJLAFRequest.h"@implementation ZJLAFRequest/** * 创建网络请求类的单例 */static ZJLAFRequest *httpRequest = nil;+ (ZJLAFRequest *)sharedInstance{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (httpRequest == nil) { httpRequest = [[self alloc] init]; } }); return httpRequest;}+(instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (httpRequest == nil) { httpRequest = [super allocWithZone:zone]; } }); return httpRequest;}- (instancetype)copyWithZone:(NSZone *)zone{ return httpRequest;}/** * GET请求 * * @param URLString 网络请求地址 * @param dict 参数(可以是字典或者nil) * @param succeed 成功后执行success block * @param failure 失败后执行failure block */- (void)GET:(NSString *)URLString dict:(id)dict progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^)(id responseObject))succeed failure:(void (^)(NSError *error))failure{ //创建网络请求管理对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //设置请求接口回来的时候支持什么类型的数据 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/xml",@"text/xml",@"text/html",nil]; //发送网络请求(请求方式为GET) [manager GET:URLString parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) { //下载进度 float downloadPro = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount; progressFloat(downloadPro); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { succeed(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];}/** * POST请求 * * @param URLString 网络请求地址 * @param dict 参数(可以是字典或者nil) * @param succeed 成功后执行success block * @param failure 失败后执行failure block */- (void)POST:(NSString *)URLString dict:(id)dict progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^)(id responseObject))succeed failure:(void (^)(NSError *error))failure{ //创建网络请求管理对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //设置请求接口回来的时候支持什么类型的数据 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/xml",@"text/xml",@"text/html",nil]; //发送网络请求(请求方式为POST) [manager POST:URLString parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) { //下载进度 float downloadPro = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount; progressFloat(downloadPro); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { succeed(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];}/** * 下载文件 * * @param URLString 网络请求地址 * @param progressFloat 当前的下载进度 * @param downLoadDic 保存下载完成的状态和路径 */-(void)DOWNLOAD:(NSString *)URLString progressFloat:(void (^)(float progressFloat))progressFloat downLoadDic:(void (^)(id responseObject))downLoadDic{ //创建管理者对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]]; //下载任务 NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { //下载进度 float downloadPro = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount; progressFloat(downloadPro); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { //下载到哪个文件夹 NSString *cachePath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject; NSString *fileName=[cachePath stringByAppendingPathComponent:response.suggestedFilename]; return [NSURL fileURLWithPath:fileName]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { //保存数据到字典 NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; if (error) [dictionary setObject:error forKey:@"error"]; //将url转成字符串去掉开头的file:再保存到字典 if ([filePath absoluteString]) { NSString *filePathStr = [filePath absoluteString]; if ([filePathStr hasPrefix:@"file:"]) { filePathStr = [[filePath absoluteString] substringFromIndex:5]; } [dictionary setObject:filePathStr forKey:@"filePath"]; } //下载完成调用的方法 downLoadDic(dictionary); }]; //开始启动任务 [task resume];}/** * 上传图片 * * @param URLString 网络请求地址 * @param dict 参数(可以是字典或者nil) * @param imageArray 保存图片的数组 * @param progressFloat 当前的上传进度 * @param succeed 上传成功 * @param failure 上传失败 */-(void)UPLOAD:(NSString *)URLString dict:(id)dict imageArray:(id)imageArray progressFloat:(void (^)(float progressFloat))progressFloat succeed:(void (^) (id responseObject))succeed failure:(void (^) (NSError *error))failure{ //创建管理者对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //设置请求接口回来的时候支持什么类型的数据 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/xml",@"text/xml",@"text/html",nil]; [manager POST:URLString parameters:dict constructingBodyWithBlock:^(id
_Nonnull formData) { //保证当前上传图片名字的唯一性,获取当前时间戳 NSDate * senddate=[NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init]; [dateformatter setDateFormat:@"YYMMddHHmmss"]; NSString * locationString=[dateformatter stringFromDate:senddate]; for (int i = 0; i < [(NSMutableArray *)imageArray count]; i ++) { //获取每一张图片转成data UIImage *image = imageArray[i]; NSData *data = UIImageJPEGRepresentation(image, 0.7); //时间戳拼接当前的i得到图片的名字 NSString *name = [locationString stringByAppendingString:[NSString stringWithFormat:@"%d",i]]; //这个就是上传的参数 [formData appendPartWithFileData:data name:name fileName:[NSString stringWithFormat:@"%@.jpg",name] mimeType:@"image/jpeg"]; } } progress:^(NSProgress * _Nonnull uploadProgress) { //打印下上传进度 float downloadPro = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount; progressFloat(downloadPro); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { succeed(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];}@end

使用方法:

先导入头文件 #import "ZJLAFRequest.h"

以post请求为例子:

NSString *hostString = @"xxxxx";    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"22",@"userid",nil];        ZJLAFRequest *httpReauest = [ZJLAFRequest sharedInstance];    [httpReauest POST:hostString dict:dic progressFloat:^(float progressFloat){            }succeed:^(id responseObject) {                //请求成功以后            } failure:^(NSError *error) {              //请求失败        NSLog(@"%@", error);            }];

 

转载于:https://my.oschina.net/linxiaoxi1993/blog/735928

你可能感兴趣的文章
web项目buildPath与lib的区别
查看>>
我的友情链接
查看>>
ifconfig:command not found的解决方法
查看>>
计算机是怎么存储数字的
查看>>
Codeforces Round #369 (Div. 2) A. Bus to Udayland 水题
查看>>
adb上使用cp/mv命令的替代方法(failed on '***' - Cross-device link解决方法)
查看>>
C++标准库简介、与STL的关系。
查看>>
Spring Boot 3 Hibernate
查看>>
查询EBS请求日志的位置和名称
查看>>
大型机、小型机、x86服务器的区别
查看>>
J2EE十三个规范小结
查看>>
算法(第四版)C#题解——2.1
查看>>
网关支付、银联代扣通道、快捷支付、银行卡支付分别是怎么样进行支付的?...
查看>>
大数据开发实战:Stream SQL实时开发一
查看>>
C++返回引用的函数例程
查看>>
dll 问题 (转)
查看>>
REST API用得也痛苦
查看>>
test for windows live writer plugins
查看>>
Tiny210 U-BOOT(二)----配置时钟频率基本原理
查看>>
代理模式
查看>>