码迷,mamicode.com
首页 > Web开发 > 详细

HTTP_异步下载

时间:2014-12-22 14:36:56      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:http   异步下载   ios   


//创建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];

}


HTTP_异步下载

标签:http   异步下载   ios   

原文地址:http://blog.csdn.net/loseway711/article/details/42078195

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!