对AFNetworking的二次封装
HttpTool.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> typedef void(^HttpSuccessBlock)(id json);
typedef void(^HttpFailureBlock)(NSError *error);
typedef void(^HttpDownloadProgressBlock)(CGFloat progress);
typedef void(^HttpUploadProgressBlock)(CGFloat progress); @interface HttpTool : NSObject /**
get网络请求 @param path url地址
@param params url参数 NSDictionary类型
@param success 请求成功 返回NSDictionary或NSArray
@param failure 请求失败 返回NSError
*/
+ (void)getWithPath:(NSString *)path
params:(NSDictionary *)params
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure; /**
post网络请求 @param path url地址
@param params url参数 NSDictionary类型
@param success 请求成功 返回NSDictionary或NSArray
@param failure 请求失败 返回NSError
*/
+ (void)postWithPath:(NSString *)path
params:(NSDictionary *)params
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure; /**
下载文件 @param path url路径
@param success 下载成功
@param failure 下载失败
@param progress 下载进度
*/
+ (void)downloadWithPath:(NSString *)path
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpDownloadProgressBlock)progress; /**
上传图片 @param path url地址
@param image UIImage对象
@param thumbName imagekey
@param params 上传参数
@param success 上传成功
@param failure 上传失败
@param progress 上传进度
*/
+ (void)uploadImageWithPath:(NSString *)path
params:(NSDictionary *)params
thumbName:(NSString *)thumbName
image:(UIImage *)image
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpUploadProgressBlock)progress; @end
HttpTool.m
#import "HttpTool.h"
#import "AFNetworking/AFNetworking.h" static NSString *kBaseUrl = SERVER_HOST; @interface AFHttpClient : AFHTTPSessionManager + (instancetype)sharedClient; @end @implementation AFHttpClient + (instancetype)sharedClient { static AFHttpClient *client = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; client = [[AFHttpClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl] sessionConfiguration:configuration];
// 接收参数类型
client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", @"text/gif", nil];
// 设置超时时间,默认60
client.requestSerializer.timeoutInterval = ;
// 安全策略
client.securityPolicy = [AFSecurityPolicy defaultPolicy];
}); return client;
} @end @implementation HttpTool + (void)getWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; [[AFHttpClient sharedClient] GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];
} + (void)postWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; [[AFHttpClient sharedClient] POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }];
} + (void)downloadWithPath:(NSString *)path success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpDownloadProgressBlock)progress { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; // 下载
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { progress(downloadProgress.fractionCompleted); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { // 获取沙盒cache路径
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { if (error) {
failure(error);
} else {
success(filePath.path);
} }]; [downloadTask resume];
} + (void)uploadImageWithPath:(NSString *)path params:(NSDictionary *)params thumbName:(NSString *)thumbName image:(UIImage *)image success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure progress:(HttpUploadProgressBlock)progress { // 获取完整的url路径
NSString *url = [kBaseUrl stringByAppendingPathComponent:path]; NSData *data = UIImagePNGRepresentation(image); [[AFHttpClient sharedClient] POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileData:data name:thumbName fileName:@"01.png" mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { progress(uploadProgress.fractionCompleted); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error);
}];
} @end
对AFNetworking的二次封装的更多相关文章
- AFNetworking二次封装的那些事
AFNetworking可是iOS网络开发的神器,大大简便了操作.不过网络可是重中之重,不能只会用AFNetworking.我觉得网络开发首先要懂基本的理论,例如tcp/ip,http协议,之后要了解 ...
- iOS项目相关@AFN&SDWeb的二次封装
一,AFNetworking跟SDWebImge是功能强大且常用的第三方,然而在实际应用中需要封装用来复用今天就跟大家分享一下AFN&SDWeb的二次封装 1. HttpClient.h及.m ...
- iOS菜鸟之AFN的二次封装
我用一个单例类将一些常用的网络请求进行了二次封装,主要包括post请求 get请求 图片文件上传下载 视频的断点续传等功能. 首先大家先去github上下载AFN,将文件夹内的AFNetworki ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- Quick Cocos (2.2.5plus)CoinFlip解析(MenuScene display AdBar二次封装)
转载自:http://cn.cocos2d-x.org/tutorial/show?id=1621 从Samples中找到CoinFlip文件夹,复制其中的 res 和 script 文件夹覆盖新建工 ...
- 对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache
虽然jquery的较新的api已经很好用了, 但是在实际工作还是有做二次封装的必要,好处有:1,二次封装后的API更加简洁,更符合个人的使用习惯:2,可以对ajax操作做一些统一处理,比如追加随机数或 ...
- Android 应用程序集成Google 登录及二次封装
谷歌登录API: https://developers.google.com/identity/sign-in/android/ 1.注册并且登录google网站 https://accounts. ...
- Android 应用程序集成FaceBook 登录及二次封装
1.首先在Facebook 开发者平台注册一个账号 https://developers.facebook.com/ 开发者后台 https://developers.facebook.com/ap ...
- 对jquery的ajax进行二次封装
第一种方法: $(function(){ /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"username": " ...
随机推荐
- Javascript怎么跳出循环,嵌套循环。
今天要实现一个功能,在数组a中的每一项,对应数组b中的每一项,如果对应上了就给数组b的checked增加ture属性,如果查找不到就给数组b的checked增加false属性. 如果有哪里写的不对欢迎 ...
- Windows Composition API 指南 - 认识 Composition API
微软在 Windows 10中 面向通用 Windows 应用 (Universal Windows Apps, UWA) 新引入了一套用于用户界面合成的 API:Composition API.Co ...
- Spring Chapter4 WebSocket 胡乱翻译 (一) 一个例子
因为没有基础,不知道从哪里入手. 文档里的例子,https://github.com/rstoyanchev/spring-websocket-portfolio,这个除了WebSocket,还整了S ...
- lua load
load (chunk [, chunkname [, mode [, env]]]) 加载一个代码块. 如果 chunk 是一个字符串,代码块指这个字符串. 如果 chunk 是一个函数, load ...
- Python 显示调用栈
Python调试不如强类型的语言方便,显示调用栈有时非常必要,inspect模块很好用 import inspect inspect.stack() inspect.stack()返回的是一个函数栈帧 ...
- flex布局的一些注意点
现在来总结下自己在项目中用flex布局的一些注意点 1.ui图中的布局方式与justify-content的布局方法不一样 这是就要利用flex-grow的空dom来分开子容器来达到页面布局的效果 2 ...
- LDAP入门与OpenLDAP使用配置
LDAP入门与OpenLDAP使用配置 1.LDAP简介 LDAP(轻量级目录访问协议,Lightweight Directory Access Protocol)是实现提供被称为目录服务的信息服务. ...
- 转:ITopologicalOperator Buffer调用异常的解决方法(来源网络)
/// <summary> /// 用拓扑分析求出缓冲区范围. /// 由于ArcGIS的问题,有时调用会出异常,因此需要循环调用 /// </summary> ...
- Matlab GUI保存图片
% --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, han ...
- flask factory
https://gist.github.com/zaccrites/c5bcf96ed90907d92042 import jinja2 from flask import Flask, render ...