关闭

有关NSURLConnection的几个问题

标签: 同步请求异步请求http请求
96人阅读 评论(0) 收藏 举报
分类:

想检测一下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 = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];
if (error ==nil) {
    NSLog(@"data:%@",data);
    NSLog(@"current_synchThread:%@",[NSThreadcurrentThread]);
    UIImage *image = [UIImageimageWithData:data ];
    imageView.image = image;
}
NSLog(@"current_synchThread_after:%@",[NSThreadcurrentThread]);

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

二、异步请求方式一

     [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 = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
[_connectstart];

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

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

    [appendDatasetLength: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 = [NSThreadcurrentThread];
    NSLog(@"currentThread:%@",thread);

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

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

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

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

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

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1110次
    • 积分:105
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类