异步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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值