1 #import "ViewController.h" 2 #import "Header.h" 3 4 @interface ViewController ()<NSURLSessionDataDelegate> 5 6 /** 7 * 用于保存相关的数据 8 */ 9 @property (nonatomic, strong) NSMutableData *resultData; 10 11 @end 12 13 @implementation ViewController 14 15 - (void)viewDidLoad { 16 [super viewDidLoad]; 17 // Do any additional setup after loading the view, typically from a nib. 18 } 19 20 // 对数据进行加载:使用NSURLSessionDataTask和NSURLSessionTask两者没有本质区别 21 // 要处理下载任务的使用使用此任务NSURLSessionDownloadTask 22 // 要处理上传任务使用:NSURLSessionUploadTask 23 24 25 #pragma mark - get请求(异步) 26 - (IBAction)getRequest:(UIButton *)sender { 27 28 // 1.创建url 29 NSURL *url = [NSURL URLWithString:GET_URL]; 30 31 32 // 2.创建session对象 33 NSURLSession *session = [NSURLSession sharedSession]; 34 35 36 // 3.创建task请求任务 37 // NSURLSession是基于任务去完成相关请求的 38 // NSURLSessionTask所有的任务都放在这里面 39 NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 40 41 // 4.解析数据 42 if (error == nil) { 43 44 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 45 NSLog(@"%@", dic); 46 } 47 }]; 48 49 50 // 5.启动任务【千万不能忘记】 51 // 原因:NSURLSessionTask实例出来的任务处于挂起状态,如果不启动,不会走block中的实现内容 52 [task resume]; 53 } 54 55 @end