iOS 同步请求和异步请求

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 10:36   11   0

在iOS里面,网络请求分为同步请求个异步请求,它俩的区别是:

同步请求:

等所有操作完全执行完毕才会继续执行 同步请求的弊端:会出现假死的情况,只要请求的操作没有完全执行完毕,就不会再去响应任何事件(在同一线程)

异步请求:

在程序运行的时候,会利用空闲的时间,去执行里面的操作,不会影响到同一线程里面的其它操作


同步请求代码实现:

  
    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];
//   实例化 请求对象 携带着 请求的数据
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
//    data 是服务器给我们响应返回的数据 NSURLConnection 发送请求 的类 sendSynchronousRequest 同步请求
 NSData *data = [NSURLConnection <span style="color:#009900;">sendSynchronousRequest</span>:request returningResponse:nil error:nil];
    UIImageView *image = [[UIImageView alloc]initWithFrame:self.view.frame];
    
    image.contentMode = UIViewContentModeScaleAspectFit;
    
    image.image = [UIImage imageWithData:data];
    
    [self.view addSubview:image];

异步请求代码实现:

 UIImageView *image = [[UIImageView alloc]initWithFrame:self.view.frame];
    
    image.contentMode = UIViewContentModeScaleAspectFit;

    [self.view addSubview:image];

    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];
    
    //   实例化 请求对象 携带着 请求的数据
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
//    发送异步请求 需要通过 连接 异步发送 请求
//    NSOperationQueue 是线程
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
//    sendAsynchronousRequest 发送一个异步请求 response 服务器回应的内容(回应状态的code,以及错误的信息)data 回应给客户端需要的数据
    [NSURLConnection <span style="color:#009900;">sendAsynchronousRequest</span>:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSLog(@"%@",response);
        
         image.image = [UIImage imageWithData:data];
        
    }];


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP