一旦AFN有较大的变动,用到AFN的项目需要更改很多的地方,为了避免这种情况,一般会对AFN封装出一个类,这样有了变动之后,只需要更改这个类即可(代码如下)
.h文件
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, RequestMethod)
{
post,
get
};
@interface NetworkTools : NSObject
+ (instancetype)shareNetworkTools;
/**
* requestMethod:请求方式
* urlString:请求地址
* parameters:请求参数
* responseBlock:请求成功或失败的回调
*/
- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;
/**
* data:上传资料
* name:上传资料的名字
* urlString:请求地址
* parameters:请求参数
* responseBlock:请求成功或失败的回调
*/
- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;
@end
.m文件
#import "NetworkTools.h"
#import <AFNetworking.h>
@implementation NetworkTools
+ (instancetype)shareNetworkTools
{
static NetworkTools *networkTools = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
networkTools = [[NetworkTools alloc] init];
});
return networkTools;
}
- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
// 定义成功的block
void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
{
responseBlock(responseObject, nil);
};
// 定义失败的block
void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
{
responseBlock(nil, error);
};
if (requestMethod == get) {
[[AFHTTPSessionManager manager] GET:urlString parameters:parameters success:success failure:failure];
} else {
[[AFHTTPSessionManager manager] POST:urlString parameters:parameters success:success failure:failure];
}
}
- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
{
responseBlock(responseObject, nil);
};
void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
{
responseBlock(nil, error);
};
[[AFHTTPSessionManager manager] POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:data name:name fileName:@"aa" mimeType:@"application/octet-stream"];
} success:success failure:failure];
}
@end
AFN与其它框架对比
AFNetWorking:简单易用,提供了基本够用的常用功能,有人更新和维护,而且目前使用者很多 。其相关资料,文档,demo很多,很好找遇到问题好解决。
ASIHttpRequest: ASI的底层基于纯C语言的CFNetwork框架,功能很强大,可惜作者已停止更新.
MKNetWorkKit:简单易用,维护和使用者少.