ANFetworking的简单使用
一:安装Pods
0.cd到项目目录
1.创建podfile文件
pod init
3.在podfile文件中输入
pod 'AFNetworking'
4.安装AFNetworking,带参数表示只安装框架 pod本身并不更新
pod install --no-repo-update
--no-repo-update Skip running `pod repo update` before install
5.安装之后使用wordspace打开
进行简单封装
二: NetworkTools的工具类的封装
#import "NetworkTools.h" @implementation NetworkTools // 单例 + (instancetype)sharedTools { static NetworkTools *tools; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // 注意:该url末尾一定要有 '/' 这个在官方文档已经写了 NSURL *baseURL = [NSURL URLWithString:@"http://www.weather.com.cn/"]; tools = [[self alloc] initWithBaseURL:baseURL]; // 设置反序列化格式 此步骤如果没有回报一个经典错误在下面 tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; }); return tools; } // 封装 , block作为参数传递 - (void)request:(NSString *)URLString parameters:(id)parameters finished:(void(^)(id result, NSError *error))finished { // 调用GET方法 [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 异步执行的时候, 执行完后成功的回调 // 这里是把block作为参数传递进来了, 在这里执行ViewController中准备好的代码 finished(responseObject, nil); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@", error); finished(nil, error); }]; } @end
经典错误: status code: 200,,但是failed: unacceptable content-type: text/html,所以要在反序列化的时候加入一个这个类型
UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ffa9d113e60> { URL: http://www.weather.com.cn/adat/sk/101010100.html } { status code: 200, headers {
Age = 159;
Connection = "keep-alive";
"Content-Type" = "text/html";
Date = "Fri, 05 Feb 2016 06:35:48 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
"X-Via" = "1.1 bianwangtong38:5 (Cdn Cache Server V2.0)";
} }, NSErrorFailingURLKey=http://www.weather.com.cn/adat/sk/101010100.html, com.alamofire.serialization.response.error.data=<7b227765 61746865 72696e66 6f223a7b 22636974 79223a22 e58c97e4 baac222c 22636974 79696422 3a223130 31303130 31303022 2c227465 6d70223a 22313022 2c225744 223a22e4 b89ce58d 97e9a38e 222c2257 53223a22 32e7baa7 222c2253 44223a22 32362522 2c225753 45223a22 32222c22 74696d65 223a2231 303a3235 222c2269 73526164 6172223a 2231222c 22526164 6172223a 224a435f 52414441 525f415a 39303130 5f4a4222 2c226e6a 64223a22 e69a82e6 97a0e5ae 9ee586b5 222c2271 79223a22 31303132 227d7d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}