逸轻紫的博客

富不学富不长,穷不学穷不尽

有关NSURLConnection的几个问题

想检测一下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);
 }

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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19411159/article/details/52384975
个人分类: 网络请求
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭