异步post请求之Block方法

 1 #import "ViewController.h"
 2 #import "Header.h"
 3 
 4 @interface ViewController ()<NSURLSessionDataDelegate>
 5 
 6 @end
 7 
 8 @implementation ViewController
 9 
10 - (void)viewDidLoad {
11     [super viewDidLoad];
12     // Do any additional setup after loading the view, typically from a nib.
13 }
14 
15 // 对数据进行加载:使用NSURLSessionDataTask和NSURLSessionTask两者没有本质区别
16 // 要处理下载任务的使用使用此任务NSURLSessionDownloadTask
17 // 要处理上传任务使用:NSURLSessionUploadTask
18 
19 
20 #pragma mark - post请求(异步)
21 - (IBAction)postRequest:(UIButton *)sender {
22     
23     // 1.创建url
24     NSURL *url = [NSURL URLWithString:POST_URL];
25 
26 
27     // 2.创建请求
28     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
29     
30     
31     // 2.5.设置body
32     // 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注)
33     NSString *dataStr = POST_BODY;
34     
35     // 对连接字符串进行编码【这一步千万不能忘记】
36     NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
37     
38     // 设置请求格式为post请求【在这里POST必须大写】
39     [request setHTTPMethod:@"POST"];
40     
41     // 设置请求体(body)
42     [request setHTTPBody:postData];
43     
44     
45     // 3.创建session对象
46     NSURLSession *session = [NSURLSession sharedSession];
47     
48     
49     // 4.创建task
50     NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
51         
52         // 5.解析
53         if (error == nil) {
54             NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
55             NSLog(@"%@", dic);
56         }
57     }];
58     
59     
60     // 6.启动任务
61     [task resume];
62     
63 }
64 
65 @end
原文地址:https://www.cnblogs.com/zhizunbao/p/5483244.html