欢迎来到 IT实训基地-南通科迅教育
咨询电话:0513-81107100
iOS开发 - AFNetworking网络请求
2017/4/25
南通科迅教育
628
南通零基础IT培训机构如何选择

AFNetworking

什么是AFN
全称是AFNetworking,是对NSURLConnection、NSURLSession的一层封装
虽然运行效率没有ASI高,但是使用比ASI简单
在iOS开发中,使用比较广泛

 

AFHTTPRequestOperationManager

是AFN中最重要的对象之一
封装了HTTP请求的常见处理
GETPOST请求
解析服务器的响应数据

创建

?
1
<codeclass="hljs"fix="">AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];</code>

GETPOST请求

?
1
2
3
4
5
6
7
8
9
10
11
12
<codeclass="hljs"erlang="">//GET请求
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void(^)(AFHTTPRequestOperation *operation, NSError *error))failure
 
//POST请求
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void(^)(AFHTTPRequestOperation *operation, NSError *error))failure
</code>

文件上传

?
1
2
3
4
5
6
<codeclass="hljs"erlang="">- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(id)parameters
       constructingBodyWithBlock:(void(^)(id  formData))block
                         success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void(^)(AFHTTPRequestOperation *operation, NSError *error))failure
</afmultipartformdata></code>

监控联网状态

?
1
2
3
4
5
6
7
8
<code bash=""class="hljs">AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager startMonitoring];
 
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@%d, status);
}];
 
</code>

提示:要监控网络连接状态,必须要先调用单例的startMonitoring方法

1.AFHTTPRequestOperationManager
* 对NSURLConnection的封装

2.AFHTTPSessionManager
* 对NSURLSession的封装

对服务器返回数据的解析

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<codeclass="hljs"erlang-repl="">1.AFN可以自动对服务器返回的数据进行解析
* 默认将服务器返回的数据当做JSON来解析
 
2.设置对服务器返回数据的解析方式
1> 当做是JSON来解析(默认做法)
* mgr.responseSerializer = [AFJSONResponseSerializer serializer];
* responseObject的类型是NSDictionary或者NSArray
 
2> 当做是XML来解析
* mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
* responseObject的类型是NSXMLParser
 
3> 直接返回data
* 意思是:告诉AFN不要去解析服务器返回的数据,保持原来的data即可
* mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
 
3.注意
* 服务器返回的数据一定要跟responseSerializer对得上
1> 服务器返回的是JSON数据
* AFJSONResponseSerializer
* AFHTTPResponseSerializer
 
2> 服务器返回的是XML数据
* AFXMLParserResponseSerializer
* AFHTTPResponseSerializer
 
3> 服务器返回的是其他数据
* AFHTTPResponseSerializer</code>

AFNetworking网络请求实例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<codeclass="hljs"java="">#importAFNetworking.h
 
@implementationViewController
 
- (void)viewDidLoad
{
    [superviewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self postJSON];
}
 
- (void)getSession
{
    // AFHTTPSessionManager 对 NSURLSession 的封装
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr GET:@ parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
 
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
 
    }];
}
 
/**
 *  利用AFN发送一个POST请求,服务器返回的JSON数据
 */
- (void)postJSON
{
    // AFHTTPRequestOperationManager 对 NSURLConnection的封装
 
    // 1.创建一个请求操作管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
 
    // 2.请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] = @哈哈哈;
    params[@pwd] =@123;
 
    // 3.发送一个GET请求
    NSString *url =@http://localhost:8080/MJServer/login;
    [mgr POST:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // 请求成功的时候调用这个block
         NSLog(@请求成功---%@, responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@请求失败);
     }];
}
 
/**
 *  利用AFN发送一个GET请求,服务器返回的JSON数据,让AFN直接返回data
 */
- (void)getData
{
    // 1.创建一个请求操作管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 声明:不要对服务器返回的数据进行解析,直接返回data即可
    // 如果是文件下载,肯定是用这个
    // responseObject的类型是NSData
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
 
    // 2.请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] = @哈哈哈;
    params[@pwd] =@123;
 
    // 3.发送一个GET请求
    NSString *url =@http://localhost:8080/MJServer/login;
    [mgr GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // 请求成功的时候调用这个block
         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
 
         NSLog(@%@, dict);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@请求失败);
     }];
}
 
/**
 *  利用AFN发送一个GET请求,服务器返回的XML数据
 */
- (void)getXML
{
    // 1.创建一个请求操作管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 声明:等会服务器返回的是XML数据
    // responseObject的类型是NSXMLParser
    mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
 
    // 2.请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] = @哈哈哈;
    params[@pwd] =@123;
    params[@type] =@XML;
 
    // 3.发送一个GET请求
    NSString *url =@http://localhost:8080/MJServer/login;
    [mgr GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // 请求成功的时候调用这个block
         NSLog(@请求成功--%@, responseObject);
//         responseObject.delegate = self;
//         [responseObject parse];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@请求失败);
     }];
}
 
/**
 *  利用AFN发送一个GET请求,服务器返回的JSON数据
 */
- (void)getJSON
{
    // 1.创建一个请求操作管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 声明一下:服务器返回的是JSON数据
    //    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    // responseObject的类型是NSDictionary或者NSArray
 
    // 2.请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] = @哈哈哈;
    params[@pwd] =@123;
 
    // 3.发送一个GET请求
    NSString *url =@http://localhost:8080/Server/login;
    [mgr GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // 请求成功的时候调用这个block
         NSLog(@请求成功---%@, responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@请求失败);
     }];
}
 
@end</code>

AFNetworking文件上传实例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<codeclass="hljs"objectivec="">#importAFNetworking.h
 
@interfaceViewController () <uinavigationcontrollerdelegate, uiactionsheetdelegate="">
@property(weak, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)upload;
@end
 
@implementationViewController
 
- (void)viewDidLoad
{
    [superviewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@请选择图片 delegate:self cancelButtonTitle:@取消 destructiveButtonTitle:nil otherButtonTitles:@拍照, @相册, nil];
    [sheet showInView:self.view.window];
}
 
#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    // 设置代理
    ipc.delegate = self;
 
    switch(buttonIndex) {
        case0: {// 拍照
            if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])return;
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            break;
        }
        case1: {// 相册
            if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])return;
            ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
        }
        default:
            break;
    }
 
    // 显示控制器
    [self presentViewController:ipc animated:YES completion:nil];
}
 
#pragma mark - UIImagePickerControllerDelegate
/**
 *  在选择完图片后调用
 *
 *  @param info   里面包含了图片信息
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // 销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
 
    // 获得图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
 
    // 显示图片
    self.imageView.image = image;
}
 
- (void)upload1
{
    // 1.创建一个管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
 
    // 2.封装参数(这个字典只能放非文件参数)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] =@123;
    params[@age] =@20;
    params[@pwd] =@456;
    params[@height] =@1.55;
 
    // 2.发送一个请求
    NSString *url =@http://localhost:8080/MJServer/upload;
    [mgr POST:url parameters:params constructingBodyWithBlock:^(id formData) {
        // 在发送请求之前会自动调用这个block
        // 需要在这个block中添加文件参数到formData中
 
        /**
         FileURL : 需要上传的文件的URL路径
         name : 服务器那边接收文件用的参数名
         fileName : (告诉服务器)所上传文件的文件名
         mimeType : 所上传文件的文件类型
         */
        NSURL *url = [[NSBundle mainBundle] URLForResource:@itcastwithExtension:@txt];
        [formData appendPartWithFileURL:url name:@filefileName:@test.txt mimeType:@text/plain error:nil];
 
        /**
         FileData : 需要上传的文件的具体数据
         name : 服务器那边接收文件用的参数名
         fileName : (告诉服务器)所上传文件的文件名
         mimeType : 所上传文件的文件类型
         */
        //        UIImage *image = [UIImage imageNamed:@minion_01];
        //        NSData *fileData = UIImagePNGRepresentation(image);
        //        [formData appendPartWithFileData:fileData name:@file fileName:@haha.png mimeType:@image/png];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@上传成功);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@上传失败);
    }];
}
 
- (IBAction)upload {
    if(self.imageView.image == nil)return;
 
    // 1.创建一个管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
 
    // 2.封装参数(这个字典只能放非文件参数)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@username] =@123;
    params[@age] =@20;
    params[@pwd] =@456;
    params[@height] =@1.55;
 
    // 2.发送一个请求
    NSString *url =@http://192.168.15.172:8080/Server/upload;
    [mgr POST:url parameters:params constructingBodyWithBlock:^(id formData) {
        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image,1.0);
        [formData appendPartWithFileData:fileData name:@filefileName:@haha.jpg mimeType:@image/jpeg];
 
        // 不是用这个方法来设置文件参数
//        [formData appendPartWithFormData:fileData name:@file];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@上传成功);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@上传失败);
    }];
 
    // 文件下载,文件比较大,断点续传技术:普遍所有的HTTP服务器都支持
    // 文件上传,文件比较大,断点续传技术:一般的HTTP服务器都不支持,常用的技术用的是Socket(TCPIP、UDP)
}
@end</afmultipartformdata></afmultipartformdata></uinavigationcontrol
77
关闭
先学习,后交费申请表
每期5位名额
在线咨询
免费电话
QQ联系
先学习,后交费
TOP
您好,您想咨询哪门课程呢?
关于我们
机构简介
官方资讯
地理位置
联系我们
0513-91107100
周一至周六     8:30-21:00
微信扫我送教程
手机端访问
南通科迅教育信息咨询有限公司     苏ICP备15009282号     联系地址:江苏省南通市人民中路23-6号新亚大厦三楼             法律顾问:江苏瑞慈律师事务所     Copyright 2008-