AFNetworking 3.0的使用

2017-06-08  本文已影响0人  HAILK

先来说一下AFNetworking从1.0到3.0的发展:

AFNetworking 1.0完全基于NSURLConnection的API;AFNetworking 2.0在基于NSURLConnection的API基础上,添加了基于NSURLSession的API选项;AFNetworking 3.0则是抛弃的NSURLConnection,完全基于NSURLSession的API.这也是基于苹果弃用NSURLConnection而不得已做出的选择.

我们在开发中会遇到许多使用AFNetworking2.X或更老的AFNetworking库,它们与最新的AFNetworking是无法兼容的.原因如下:

1.AFNetworking 3.0移除了下面三个类

AFURLConnectionOperation

AFHTTPRequestOperation

AFHTTPRequestOperationManager

2.AFNetworking 3.0修改了下面三个类

UIImageView+AFNetworking

UIWebView+AFNetworking

UIButton+AFNetworking

对以上类的移除和修改导致了AFNetworking3.0无法向上兼容.所以我们在AFNetworking3.0的环境下,就不能去使用AFNetworking3.0之前封装的网络工具类了.解决办法有两个,一个是修改网络工具类,另一个就是重写网络工具类(好吧,其实这就是一个方法).

如何使用AFNetworking3.0重写网络工具类?

1.建立会话

AFHTTPSessionManager *session =[AFHTTPSessionManager manager];

session.requestSerializer=[AFJSONRequestSerializer serializer];

NSMutableDictionary*parameters=[NSMutableDictionary dictionary];

parameters[@"start"] =@"1";

parameters[@"end"] =@"5";

2.get请求

[session GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

failureBlock(error);

}];

3.post请求

[session POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

failureBlock(error);

}];

封装一个通用的网络请求方式:

1.单例类

+ (instancetype)sharedTools {

static QLMNetworkTools *tools;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

tools = [[QLMNetworkTools alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.baidu.com"]];

tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

});

return tools;

}

2.通用的请求方式

- (void)requestWithType: (RequestType)requestType andUrlStr: (NSString *)urlStr andParams: (id)parameters andSuccess: (void (^)(id responseObject))successBlock andFailture: (void (^)(NSError *error))failureBlock{

if (requestType == GET) {

[self GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

failureBlock(error);

}];

} else {

[self POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

failureBlock(error);

}];

}

}

上一篇下一篇

猜你喜欢

热点阅读