AFNetworking之小试牛刀
2015-11-24 本文已影响1446人
J_mailbox
导语:
众所周知,AFNetworking是目前IOS开发中非常受欢迎的第三方网络通信类库,同时AFNetworking对苹果官方NSURLConnection和NSURLSession进行了封装,使用起来可以说是简单的"令人发指".
官网地址:
AFNetworking有关请求与响应的信息
请求:(序列化)
AFURLRequestSerialization
AFHTTPRequestSerializer(默认) 传输的就是二进制
AFJSONRequestSerializer 传输入的二进制是一个JSON格式的二进制 ,只有NSArray,NSDictionay
AFPropertyListRequestSerializer 传输的到时候是一个plist,这个不玩意儿不用,因为他不通用
响应:(反序列化)
<AFURLResponseSerialization>
AFHTTPResponseSerializer //返回的就一个纯洁的二进制
AFJSONResponseSerializer(默认) 返回的是一个JSON格式的二进制,并且AFN帮我们自动序列化成了字典或是数组
AFXMLParserResponseSerializer XMLParser
AFXMLDocumentResponseSerializer (Mac OS X) 不适合我们的iOS
AFPropertyListResponseSerializer plist
AFImageResponseSerializer //国片
AFCompoundResponseSerializer //混合
使用AFNetworking
- GET方法:
//1.首先创建一个管理者
AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
//2.发送请求
//在使用AFN的时候,直接传递我们url的字符串就可以了
//AFN在反序列化的时候,默认是帮我们按照JSON的格式去解析
[manager GET:@"http://localhost/test.json" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
//第一个参数 operation 操作
//第二个参数 responseObject
NSLog(@"%@---%@",responseObject,[responseObject class]);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
- POST方法:
//1.创建一个基于NSURLConnection的管理
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//2.发送我们的POST请求
//用户名密码
NSDictionary *param = @{@"username":@"admin",@"password":@"123"};
//登陆到得网址
[manager POST:@"http://localhost/login.php" parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"post result====%@---%@",responseObject,[responseObject class]);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
- AFNetworking之搭配webView使用
注意:因为默认情况下AFNetworking的响应解析方式都是按照JOSN解析,所以我们需要修改AFNetworking的解析方式,但是为了以后使用方便,我们不在AFNetworking基础上修改,我们添加一个类继承自AFHTTPSessionManager然后创建一个单例,这样以后AFNetworking更新,我们的代码也不会因此受到影响.
首先创建NetWorkTool类,并创建单例方法
#import "AFHTTPSessionManager.h"
@interface NetWorkTool : AFHTTPSessionManager
//单例
+ (instancetype)sharedNetWorkTool;
@end
实现单例方法
#import "NetWorkTool.h"
@implementation NetWorkTool
static NetWorkTool *_instance;
+ (instancetype)sharedNetWorkTool{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[NetWorkTool alloc] initWithBaseURL:nil];
_instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//默认情况下的响应解析方式,就是不管服务器给我们返回的是什么,都按照JSON去解析
//将默认的JSON序列化方式,改成我们最普通的二进制
_instance.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return _instance;
}
@end
在控制器中拖入一个UIWebView试图,通过连线方式连接到控制器中
#import "ViewController.h"
#import "NetWorkTool.h"
@interface ViewController ()
//WebView
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadWebView];
}
- (void)loadWebView{
//1.获取我们NetWorkTool的单例
NetWorkTool *netWorkTool = [NetWorkTool sharedNetWorkTool];
//2.发送GET请求 //html
__weak typeof(self) weakSelf = self;
[netWorkTool GET:@"http://www.baidu.com" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(@"result===%@----%@",responseObject,[NSThread currentThread]);
//再将我们返回的二进制,转成我们字符串,反序列化
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//在主线程更新UI
[weakSelf.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error===%@",[error localizedDescription]);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
- AFNetworking之联网检测
联网检测对应状态
AFNetworkReachabilityStatusUnknown = -1, //未知的状态
AFNetworkReachabilityStatusNotReachable = 0, //不能联网
AFNetworkReachabilityStatusReachableViaWWAN = 1, //流量
AFNetworkReachabilityStatusReachableViaWiFi = 2, //wifi
//点击屏幕的时候开始检测
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"%ld",status);
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
- AFNetworking之上传文件
//点击屏幕的时候上传文件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//获取基于NSURLSession的管理器
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
//上传文件
NSDictionary *param=@{@"status":@"this is test"};
[manager POST:@"http://localhost/post/upload-m.php" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//获取文件1
NSURL *url1=[[NSBundle mainBundle]URLForResource:@"01.jpg" withExtension:nil];
[formData appendPartWithFileURL:url1 name:@"userfile[]" fileName:@"01.jpg" mimeType:@"image/png" error:NULL];
//获取文件2
NSURL *url2=[[NSBundle mainBundle]URLForResource:@"02.jpg" withExtension:nil];
NSData *data2=[NSData dataWithContentsOfURL:url2];
//[formData appendPartWithFileData:data2 name:@"userfile[]" fileName:@"02.jpg" mimeType:@"image/png"];
//application/octet-stream通用格式
[formData appendPartWithFileData:data2 name:@"userfile[]" fileName:@"02.jpg" mimeType:@"application/octet-stream"];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(@"responseObject--->%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error---->%@",error);
}];
}