想检测一下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);
}
相关运行结果如下图: