异步post请求之Block方法

时间:2023-03-09 08:31:20
异步post请求之Block方法
 #import "ViewController.h"
#import "Header.h" @interface ViewController ()<NSURLSessionDataDelegate> @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} // 对数据进行加载:使用NSURLSessionDataTask和NSURLSessionTask两者没有本质区别
// 要处理下载任务的使用使用此任务NSURLSessionDownloadTask
// 要处理上传任务使用:NSURLSessionUploadTask #pragma mark - post请求(异步)
- (IBAction)postRequest:(UIButton *)sender { // 1.创建url
NSURL *url = [NSURL URLWithString:POST_URL]; // 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 2.5.设置body
// 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注)
NSString *dataStr = POST_BODY; // 对连接字符串进行编码【这一步千万不能忘记】
NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding]; // 设置请求格式为post请求【在这里POST必须大写】
[request setHTTPMethod:@"POST"]; // 设置请求体(body)
[request setHTTPBody:postData]; // 3.创建session对象
NSURLSession *session = [NSURLSession sharedSession]; // 4.创建task
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 5.解析
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dic);
}
}]; // 6.启动任务
[task resume]; } @end