iOS 同步请求和异步请求

在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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值