zoukankan      html  css  js  c++  java
  • 异步get请求之Block方法

     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
  • 相关阅读:
    php学习笔记
    附加题-重构的读后总结
    附加题-stack的理解
    (转)php的扩展和嵌入--php的生命周期与变量详述
    homework-09
    html学习笔记之position
    homework-06
    homework-08
    在windows下使用git需要反复输入用户名和密码的问题
    windows命令行编码与nodejs编码格式冲突的解决方式
  • 原文地址:https://www.cnblogs.com/zhizunbao/p/5482878.html
Copyright © 2011-2022 走看看