AFNetWorking 框架使用笔记

2017-04-09  本文已影响43人  Pluto大叔

最近初识大名顶顶AFNetWorking框架,用来处理iOS项目中的网络通讯相关的功能,这里主要是把我在项目中遇到的一些问题进行一下整合,也希望能够帮助其他有类似需求的人。

AFNetWorking LogoAFNetWorking Logo

AFNetWorking框架介绍

AF框架应该不需要多说,一个非常方便的网络请求库,可以轻松实现各种网络请求,比如经常使用的GET请求、POST请求,以及上传多张图片等。正如同他们的官方介绍:

Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.

git地址为:AFNetWorking-Git .

3.x的变化

在AFNetWorking 3.0中已经废弃了所有基于NSURLConnection API 的支持,取出了AFURLConnectionOperationAFHTTPRequestOperationAFHTTPRequestOperationManager,其他基于NSURLConnection的方法全部用NSURLSession重构。

如何使用AFNetWorking框架

// NSURLSessionConfiguration来统一配置NSURLSession,比如请求超时等等参数
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//初始化一个AFHTTPSessionManager
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
// POST 请求
[manager POST:@"https://api.netease.im/nimserver/user/create.action" parameters:parame progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"请求中");
    } success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        [self doSomething:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败了:%@",error);
    }];
// GET请求
[manager GET:(nonnull NSString *) parameters:(nullable id) progress:^(NSProgress * _Nonnull downloadProgress) {
       // 请求中时需要处理的code
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       // 请求成功后的返回对象
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败返回的错误信息
    }];

    [manager.requestSerializer setValue:appKey forHTTPHeaderField:@"AppKey"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:curTime forHTTPHeaderField:@"CurTime"];
    [manager.requestSerializer setValue:checkSum forHTTPHeaderField:@"CheckSum"];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
上一篇 下一篇

猜你喜欢

热点阅读