有关NSURLConnection的几个问题

本文通过实例对比了NSURLConnection同步请求与两种异步请求的区别。同步请求会阻塞UI线程直到请求完成;异步请求则不会阻塞主线程,并且可以在数据到达时更新UI。此外还介绍了异步请求中数据接收的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想检测一下NSURLConnection的几种网络请求的使用方法的区别,做了以下几步:
1.从百度扒了一张图片地址,作为下载源;
2.做如下编写:

appendData = [NSMutableData new];
NSString *imageUrl = @"http://img5.duitang.com/uploads/item/201410/08/20141008205721_JUaJS.jpeg";
NSURL *url = [NSURL URLWithString:[imageUrl   stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

NSURLResponse *response = nil;
NSError *error = nil;
NSOperationQueue *queue = [[NSOperationQueue alloc]init];

一、同步请求

NSData *data = [NSURLConnection sendSynchronousRequest:requestreturningResponse:&responseerror:&error];
if (error ==nil) {
    NSLog(@"data:%@",data);
    NSLog(@"current_synchThread:%@",   [NSThread currentThread]);
    UIImage *image = [UIImage imageWithData:data ];
    imageView.image = image;
}
NSLog(@"current_synchThread_after:%@",[NSThread currentThread]);

注一:通过同步请求方式发现,同步请求等待数据完全返回之后才往下执行。

二、异步请求方式一

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * __nullable response,NSData * __nullable data,NSError *__nullable error){
     if (error) {
        NSLog(@"error=%@,",error.localizedDescription);
    }else{

        NSLog(@"data_length:%d",[data length]);
        NSLog(@"current_synchThread:%@",[NSThread currentThread]);

        dispatch_sync(dispatch_get_main_queue(), ^{

            UIImage *image = [UIImage imageWithData:data ];
            imageView.image = image;
        });

        NSLog(@"data:%@",data);
    }
}];

NSLog(@"current_synchThread_after:%@",[NSThread currentThread]);

注二:通过打印发现,current_synchThread 并不是主线程,说明此方法进行时会重新开辟线程;此外current_synchThread_after会在返回data数据之前执行,进一步证明了这是个异步请求方式。

三、 异步请求方式二

_connect = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[_connect start];

/* 异步方式二的代理方法/

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    [appendData setLength:0];

    NSLog(@"response:%@",response.description);
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *allHeaderFilders = [httpResponse allHeaderFields];
    NSLog(@"allHeader:%@",allHeaderFilders);

    long long totalLength = [[allHeaderFilders objectForKey:@"Content-Length"]longLongValue];
    NSLog(@"totalLength:%lld",totalLength);

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    NSThread *thread = [NSThread currentThread];
    NSLog(@"currentThread:%@",thread);

    [appendData appendData:data];
    NSLog(@"data_length:%d",[appendDatalength]);
    UIImage *image = [UIImage imageWithData:appendData];
    imageView1.image = image;
    if ([appendData length]) {
         [_connectcancel];
    }
    NSLog(@"data:%@",appendData);
 }

注三:这里在返回数据的时候是分批返回的,当返回第一批数据时,我用了[_connect cancel]去停止链接,这时候加载图片发现图片只加载了上半部分,对照数据data也发现是完全加载的数据的前半部分。

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"finish");
 }

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"error:%@",error.localizedDescription);
 }

相关运行结果如下图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值