iOS UIImageView显示网络图片的基础用法

先解释下以下代码中的变量:
picsURL是一个存储URL地址的数组
choice是选择图片的索引数
self.imageView是View中的UIImageView
其实显示一幅网络上的图片十分简单,如下2行代码即可。
UIImage *image=[UIImage imageWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:[picsURL objectAtIndex:choice]]]];
[self.imageView setImage:image];


但是这种方法是同步获取的,如果图片十分大的话,界面就会卡死了,所以一般采取异步方式来获取,如下:
_data是一个NSMutableData
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{
//可以在显示图片前先用本地的一个loading.gif来占位。
   UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"loading.gif"];
   [self.imageView setImage:img];
   _data = [[NSMutableDataalloc] init];
   //保存接收到的响应对象,以便响应完毕后的状态。
   _response = response;
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
//_data为NSMutableData类型的私有属性,用于保存从网络上接收到的数据。
//也可以从此委托中获取到图片加载的进度。
   [_data appendData:data];
   NSLog(@"%lld%%", data.length/_response.expectedContentLength * 100);
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{
   //请求异常,在此可以进行出错后的操作,如给UIImageView设置一张默认的图片等。
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection{
   //加载成功,在此的加载成功并不代表图片加载成功,需要判断HTTP返回状态。
   NSHTTPURLResponse*response=(NSHTTPURLResponse*)_response;
   if(response.statusCode == 200){
        //请求成功
        UIImage *img=[UIImage imageWithData:_data];
        [self.imageView setImage:img];
   }
}


这样就可以异步来加载图片了,提升了用户体验。

猜你喜欢

转载自iaiai.iteye.com/blog/2128163