AFNetworking3.0以上版本的封装--封装代码(升级版
2017-10-20 本文已影响26人
韩发发吖
这之前写过一篇《AFN3.0以上版本的二次封装》,主要为当时公司的项目服务,写的针对性比较强。做过几个不同的项目后,对网络请求的理解更加清晰了,因此写下了这篇升级版。之前那篇文章写过的一些细下模块,这里就不做太多的重复介绍了,这里主要写下大众适用模块。
封装AFN目的:
1、降低工程代码耦合度,提高网络请求的内聚度。(比较官方的说法,主要是直接使用显得太low
)
2、降低代码工作量,统一管理调用。(懒人适用,减少工作量
)
3、为以后接替这个工程的后期迭代、维护。(利人利己,还有一点代码洁癖
)
老生常谈:Request_method的规则(这里的规则一定要和后台人员沟通,以便后期写请求的时候,各种隐患问题,还有就是既然给出这种规则,就一定具有它的道理
):
- GET:获取资源,不会改动资源
- POST:创建记录
- PATCH:改变资源状态或更新部分属性
- PUT:更新全部属性
- DELETE:删除资源
封装AFN做法:
1、在新建的项目工程中引入AFNetworking(以下简称AFN
),这里的AFN最好使用cocoapods引入,版本在3.0及其以上。
2、新建类,继承NSObject, 引入“AFNetworking.h”
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
@interface PCNetworkManager : NSObject
@end
封装AFN代码:
.h文件
// PCNetworkManager.h
// AFNTestDemo
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
/**
* GET:获取资源,不会改动资源
* POST:创建记录
* PATCH:改变资源状态或更新部分属性
* PUT:更新全部属性
* DELETE:删除资源
*/
typedef NS_ENUM(NSUInteger, HTTPMethod) {
HTTPMethodGET,
HTTPMethodPOST,
HTTPMethodPUT,
HTTPMethodPATCH,
HTTPMethodDELETE,
};
@interface PCNetworkManager : NSObject
/**
* 单例
*
* @return 网络请求类的实例
*/
+ (nonnull instancetype)defaultManager ;
#pragma mark 常用网络请求方式
/**
常用网络请求方式
@param requestMethod 请求方试
@param serverUrl 服务器地址
@param apiPath 方法的链接
@param parameters 参数
@param progress 进度
@param success 成功
@param failure 失败
@return return value description
*/
- (nullable NSURLSessionDataTask *)sendRequestMethod:(HTTPMethod)requestMethod
serverUrl:(nonnull NSString *)serverUrl
apiPath:(nonnull NSString *)apiPath
parameters:(nullable id)parameters
progress:(nullable void (^)(NSProgress * _Nullable progress))progress
success:(nullable void(^) (BOOL isSuccess, id _Nullable responseObject))success
failure:(nullable void(^) (NSString * _Nullable errorMessage))failure ;
#pragma mark POST 上传图片
/**
上传图片
@param serverUrl 服务器地址
@param apiPath 方法的链接
@param parameters 参数
@param imageArray 图片
@param width 图片宽度
@param progress 进度
@param success 成功
@param failure 失败
@return return value description
*/
- (nullable NSURLSessionDataTask *)sendPOSTRequestWithserverUrl:(nonnull NSString *)serverUrl
apiPath:(nonnull NSString *)apiPath
parameters:(nullable id)parameters
imageArray:(NSArray *_Nullable)imageArray
targetWidth:(CGFloat )width
progress:(nullable void (^)(NSProgress * _Nullable progress))progress
success:(nullable void(^) (BOOL isSuccess, id _Nullable responseObject))success
failure:(nullable void(^) (NSString *_Nullable error))failure ;
@end
.m文件
// PCNetworkManager.m
// AFNTestDemo
#import "PCNetworkManager.h"
@interface PCNetworkManager ()
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
@end
@implementation PCNetworkManager
static PCNetworkManager *networkManager = nil;
/**
* 单例
*
* @return 网络请求类的实例,可在请求时直接调用方法,也是一个直接初始化的方式
*/
+ (instancetype)defaultManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!networkManager) {
networkManager = [[PCNetworkManager alloc] init];
}
});
return networkManager;
}
/**
初始化,APP每次启动时会调用该方法,运行时不会调用
@return 基本的请求设置
*/
- (instancetype)init {
if (self = [super init]) {
self.sessionManager = [AFHTTPSessionManager manager];
// 设置请求以及相应的序列化器
self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
// 设置超时时间
self.sessionManager.requestSerializer.timeoutInterval = 10.0;
// 设置响应内容的类型
self.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
}
return self;
}
#pragma mark 常用网络请求
/**
常用网络请求方式
@param requestMethod 请求方试
@param serverUrl 服务器地址
@param apiPath 方法的链接
@param parameters 参数
@param progress 进度
@param success 成功
@param failure 失败
@return return value description
*/
- (nullable NSURLSessionDataTask *)sendRequestMethod:(HTTPMethod)requestMethod
serverUrl:(nonnull NSString *)serverUrl
apiPath:(nonnull NSString *)apiPath
parameters:(nullable id)parameters
progress:(nullable void (^)(NSProgress * _Nullable progress))progress
success:(nullable void(^) (BOOL isSuccess, id _Nullable responseObject))success
failure:(nullable void(^) (NSString * _Nullable errorMessage))failure {
// 请求的地址
NSString *requestPath = [serverUrl stringByAppendingPathComponent:apiPath];
NSURLSessionDataTask * task = nil;
switch (requestMethod) {
case HTTPMethodGET:
{
task = [self.sessionManager GET:requestPath parameters:parameters progress:progress success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(YES,responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure([self failHandleWithErrorResponse:error task:task]);
}
}];
}
break;
case HTTPMethodPOST:
{
task = [self.sessionManager POST:requestPath parameters:parameters progress:progress success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(YES,responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure([self failHandleWithErrorResponse:error task:task]);
}
}];
}
break;
case HTTPMethodPUT:
{
task = [self.sessionManager PUT:requestPath parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(YES,responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure([self failHandleWithErrorResponse:error task:task]);
}
}];
}
break;
case HTTPMethodPATCH:
{
task = [self.sessionManager PATCH:requestPath parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(YES,responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure([self failHandleWithErrorResponse:error task:task]);
}
}];
}
break;
case HTTPMethodDELETE:
{
task = [self.sessionManager DELETE:requestPath parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(YES,responseObject);
} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure([self failHandleWithErrorResponse:error task:task]);
}
}];
}
break;
}
return task;
}
#pragma mark POST 上传图片
/**
上传图片
@param serverUrl 服务器地址
@param apiPath 方法的链接
@param parameters 参数
@param imageArray 图片
@param width 图片宽度
@param progress 进度
@param success 成功
@param failure 失败
@return return value description
*/
- (nullable NSURLSessionDataTask *)sendPOSTRequestWithserverUrl:(nonnull NSString *)serverUrl
apiPath:(nonnull NSString *)apiPath
parameters:(nullable id)parameters
imageArray:(NSArray *_Nullable)imageArray
targetWidth:(CGFloat )width
progress:(nullable void (^)(NSProgress * _Nullable progress))progress
success:(nullable void(^) (BOOL isSuccess, id _Nullable responseObject))success
failure:(nullable void(^) (NSString *_Nullable error))failure {
// 请求的地址
NSString *requestPath = [serverUrl stringByAppendingPathComponent:apiPath];
NSURLSessionDataTask * task = nil;
task = [self.sessionManager POST:requestPath parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSUInteger i = 0 ;
// 上传图片时,为了用户体验或是考虑到性能需要进行压缩
for (UIImage * image in imageArray) {
// 压缩图片,指定宽度(注释:imageCompressed:withdefineWidth:图片压缩的category)
UIImage * resizedImage = [UIImage imageCompressed:image withdefineWidth:width];
NSData * imgData = UIImageJPEGRepresentation(resizedImage, 0.5);
// 拼接Data
[formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
i++;
}
} progress:progress success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success)success(YES,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) failure([self failHandleWithErrorResponse:error task:task]);
;
}];
return task;
}
#pragma mark 报错信息
/**
处理报错信息
@param error AFN返回的错误信息
@param task 任务
@return description
*/
- (NSString *)failHandleWithErrorResponse:( NSError * _Nullable )error task:( NSURLSessionDataTask * _Nullable )task {
__block NSString *message = nil;
// 这里可以直接设定错误反馈,也可以利用AFN 的error信息直接解析展示
NSData *afNetworking_errorMsg = [error.userInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey];
DebugLog(@"afNetworking_errorMsg == %@",[[NSString alloc]initWithData:afNetworking_errorMsg encoding:NSUTF8StringEncoding]);
if (!afNetworking_errorMsg) {
message = @"网络连接失败";
}
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSInteger responseStatue = response.statusCode;
if (responseStatue >= 500) { // 网络错误
message = @"服务器维护升级中,请耐心等待";
} else if (responseStatue >= 400) {
// 错误信息
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:afNetworking_errorMsg options:NSJSONReadingAllowFragments error:nil];
message = responseObject[@"error"];
}
DebugLog(@"error == %@",error);
return message;
}
@end
注:如若发现错误请与我联系,我会及时修改本篇文章