HTTP_异步下载


//创建imageVIew对象

- (void)createImageView

{

    UIImageView *imageView = [[UIImageView alloc]init]; //1

    imageView.frame = CGRectMake(30, 120, 300, 400);

    imageView.backgroundColor = [UIColor redColor];

    [self.view addSubview:imageView];//2

    //[imageView release] //1(ARC内存管理系统自动释放)

    _imageView = imageView;

}

//创建下载按钮

- (void)createBtn

{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];

    btn.frame = CGRectMake(50, 50, 200, 50);

    [btn setTitle:@"下载数据" forState:UIControlStateNormal];

    btn.titleLabel.font = [UIFont systemFontOfSize:26];

    btn.backgroundColor = [UIColor orangeColor];

    [btn addTarget:self action:@selector(downLoadData) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

//实现下载数据方法

- (void)downLoadData

{

    //1.创建url对象

    NSURL *url = [NSUR URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D310/sign=72d5d600362ac65c67056072cbf3b21d/8435e5dde71190ef3e9498bfcd1b9d16fdfa6066.jpg"];

    //2.创建请求对象

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

    //3.创建异步下载连接对象

    //参数1:请求对象

    //参数2:代理对象,由于是异步下载,则调用了这行代码后会立即执行后续的代码,只有通过代理对象实现协议的方法来接收服务器传过来的信息

    //参数3:开始标志,是否立即启动yes:立即启动 no:手动启动(需调用start方法)

    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];

    //同步下载数据,会让UI主线程阻塞,因为主线程会一直等待数据下载完成或者下载出错返回才能继续往下执行进入事件循环当中(runLoop)

    //异步下载数据,UI主线程会开启一个新的线程,然后让线程去做下载的事情,然后立马往下执行进入事件循环,并且通过代理协议传递给代理对象处理相应的数据或调用方法处理数据

    //4.手动开始启动连接(通过三次握手建立连接)

    [conn start]; 

}


#pragma mark-连接协议方法 NSURLConnectionDelegate

//1.传输失败调用方法

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

{

    NSLog(@"传输失败,error=%@",error);

}


#pragma mark-连接数据协议方法 NSURLConnectionDataDelegate

//1.收到应答包调用方法

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

{

    NSLog(@"收到应答包,responese=%@",response);

}

//2.收到数据包调用方法,这个方法会被调用多次

//当数据比较大的时候,服务器会将数据分块传输

//当本地有缓存时,这个方法只调用一次,即在获取到本地缓存的数据时调用

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

{

    NSLog(@"收到数据");

    //2.1保存每次取到的数据,因为数据可能会分多次传输

    [_data appendData:data];

}

//3.结束传输数据调用方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"下载完成");

    //3.1将数据转成图片对象

    UIImage *image = [UIImage imageWithData:_data];

    //3.2将图片对象传给imageView

    _imageView.image = image;

    //3.3清空保存的数据

    [_data setLength:0];

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值