#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic,copy)NSString *myUrlStr;
//接收数据用的data
@property (nonatomic,strong)NSMutableData *result;
//记录数据的总大小
@property (nonatomic,assign)float totalSize;
@end
@implementation ViewController
/*
Connection
1.同步请求:一般不怎么用
2.异步请求:block方式
3.异步请求:代理模式
*/
-(NSMutableData *)result
{
if (!_result)
{
_result = [NSMutableData new];
}
return _result;
}
- (IBAction)btnDownLoad:(UIButton *)sender
{
// [self syncDownloadWithConnection];
// [self asyncDownloadWithConnectionBlock];
[self asyncDownloadWithConnectionDelegate];
}
#pragma mark -同步-
-(void)syncDownloadWithConnection
{
//1.将字符串地址转换成URL
NSURL *url = [NSURL URLWithString:_myUrlStr];
//2.将URL封装成NSURLRequest对象,可悲Connection使用
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.connection建立网络连接
//给出所需的参数
NSURLResponse *response;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(@"%@",error);
return;
}
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
}
#pragma mark -异步-
//代理模式
-(void)asyncDownloadWithConnectionDelegate
{
//1.将字符串地址转换成URL
NSURL *url = [NSURL URLWithString:_myUrlStr];
//2.将URL封装成NSURLRequest对象,可被Connection使用
//NSURLRequestReloadIgnoringLocalCacheData 忽略本地缓存
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
//3.代理方法,异步请求数据
[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark -NSURLConnectionDataDelegate-
//调用它就证明,连接有响应,已经下载完相应头,开始下载
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.progressView.hidden = NO;
//expectedContentLength 获取数据的总长度
self.totalSize = response.expectedContentLength;
self.result.length = 0;
}
//调用它就证明,正在接收数据,响应体,根据数据的大小,会不间断的接收,直至全部完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//不间断接收数据
[self.result appendData:data];
//获取进度比
float pv = self.result.length / self.totalSize;
//刷新进度(当前就是主线程,可以不去获取,如果不清楚,最好获取主线程去刷新UI)
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.progress = pv;
});
}
//调用它就证明下载完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:self.result];
});
}
//连接发生错误,下载失败(1.断网 2.网址错误)
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@“%@“,error);
}
//block模式
-(void)asyncDownloadWithConnectionBlock
{
//显示加载圈
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//1.将字符串地址转换成URL
NSURL *url = [NSURL URLWithString:_myUrlStr];
//2.将URL封装成NSURLRequest对象,可悲Connection使用
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"%@",[NSThread currentThread]);
NSLog(@"开始请求");
//3.异步请求(block形式,iOS5.0之后推出的方法)
//给出相关参数queue
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError)
{
NSLog(@"block返回");
NSLog(@"%@",[NSThread currentThread]);
NSLog(@"响应:%@",response);
/*
//第一种判断方式
if (!connectionError && data)
{
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
}*/
//第二种判断方式
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
}
//关闭加载圈
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
/*
block优点:方便使用,比如json请求
缺点:整体返回,不能分布接收,不能显示进度
*/
}];
NSLog(@"下载完成");
}
- (void)viewDidLoad {
[super viewDidLoad];
_myUrlStr = @"http://pic18.nipic.com/20111130/8885119_125321390000_2.jpg";
self.progressView.hidden = YES;
}
@end
NSURLConnection的3种请求方式
最新推荐文章于 2020-05-08 13:22:25 发布