本文转载至 http://blog.csdn.net/enuola/article/details/8639404 
最近做一个项目,需要用到UITableView异步加载图片的例子,看到网上有一个EGOImageView的很好的例子。

但是由于,EGOImageView的实现比较复杂,于是自己就动手做了一个AsynImageView,同样可以实现EGOImageView的效果。

而且自己写的代码比较清晰,容易理解,同样可以实现指定placehoderImage以及指定imageURL,来进行图片的异步加载。

同时,如果图片已经请求过,则不会再重复请求网络,会直接读取本地缓存文件。

效果如下:

具体实现思路如下:

AsynImageView.h的文件内容:

[cpp] view plaincopy
  1. #import <UIKit/UIKit.h>
  2. @interface AsynImageView : UIImageView
  3. {
  4. NSURLConnection *connection;
  5. NSMutableData *loadData;
  6. }
  7. //图片对应的缓存在沙河中的路径
  8. @property (nonatomic, retain) NSString *fileName;
  9. //指定默认未加载时,显示的默认图片
  10. @property (nonatomic, retain) UIImage *placeholderImage;
  11. //请求网络图片的URL
  12. @property (nonatomic, retain) NSString *imageURL;
  13. @end

AsynImageView.m中的文件内容:

[cpp] view plaincopy
  1. #import "AsynImageView.h"
  2. #import <QuartzCore/QuartzCore.h>
  3. @implementation AsynImageView
  4. @synthesize imageURL = _imageURL;
  5. @synthesize placeholderImage = _placeholderImage;
  6. @synthesize fileName = _fileName;
  7. - (id)initWithFrame:(CGRect)frame
  8. {
  9. self = [super initWithFrame:frame];
  10. if (self) {
  11. // Initialization code
  12. self.layer.borderColor = [[UIColor whiteColor] CGColor];
  13. self.layer.borderWidth = 2.0;
  14. self.backgroundColor = [UIColor grayColor];
  15. }
  16. return self;
  17. }
  18. //重写placeholderImage的Setter方法
  19. -(void)setPlaceholderImage:(UIImage *)placeholderImage
  20. {
  21. if(placeholderImage != _placeholderImage)
  22. {
  23. [_placeholderImage release];
  24. _placeholderImage = placeholderImage;
  25. self.image = _placeholderImage;    //指定默认图片
  26. }
  27. }
  28. //重写imageURL的Setter方法
  29. -(void)setImageURL:(NSString *)imageURL
  30. {
  31. if(imageURL != _imageURL)
  32. {
  33. self.image = _placeholderImage;    //指定默认图片
  34. [_imageURL release];
  35. _imageURL = [imageURL retain];
  36. }
  37. if(self.imageURL)
  38. {
  39. //确定图片的缓存地址
  40. NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
  41. NSString *docDir=[path objectAtIndex:0];
  42. NSString *tmpPath=[docDir stringByAppendingPathComponent:@"AsynImage"];
  43. NSFileManager *fm = [NSFileManager defaultManager];
  44. if(![fm fileExistsAtPath:tmpPath])
  45. {
  46. [fm createDirectoryAtPath:tmpPath withIntermediateDirectories:YES attributes:nil error:nil];
  47. }
  48. NSArray *lineArray = [self.imageURL componentsSeparatedByString:@"/"];
  49. self.fileName = [NSString stringWithFormat:@"%@/%@", tmpPath, [lineArray objectAtIndex:[lineArray count] - 1]];
  50. //判断图片是否已经下载过,如果已经下载到本地缓存,则不用重新下载。如果没有,请求网络进行下载。
  51. if(![[NSFileManager defaultManager] fileExistsAtPath:_fileName])
  52. {
  53. //下载图片,保存到本地缓存中
  54. [self loadImage];
  55. }
  56. else
  57. {
  58. //本地缓存中已经存在,直接指定请求的网络图片
  59. self.image = [UIImage imageWithContentsOfFile:_fileName];
  60. }
  61. }
  62. }
  63. //网络请求图片,缓存到本地沙河中
  64. -(void)loadImage
  65. {
  66. //对路径进行编码
  67. @try {
  68. //请求图片的下载路径
  69. //定义一个缓存cache
  70. NSURLCache *urlCache = [NSURLCache sharedURLCache];
  71. /*设置缓存大小为1M*/
  72. [urlCache setMemoryCapacity:1*124*1024];
  73. //设子请求超时时间为30s
  74. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.imageURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
  75. //从请求中获取缓存输出
  76. NSCachedURLResponse *response = [urlCache cachedResponseForRequest:request];
  77. if(response != nil)
  78. {
  79. //            NSLog(@"如果又缓存输出,从缓存中获取数据");
  80. [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
  81. }
  82. /*创建NSURLConnection*/
  83. if(!connection)
  84. connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
  85. //开启一个runloop,使它始终处于运行状态
  86. UIApplication *app = [UIApplication sharedApplication];
  87. app.networkActivityIndicatorVisible = YES;
  88. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  89. }
  90. @catch (NSException *exception) {
  91. //        NSLog(@"没有相关资源或者网络异常");
  92. }
  93. @finally {
  94. ;//.....
  95. }
  96. }
  97. #pragma mark - NSURLConnection Delegate Methods
  98. //请求成功,且接收数据(每接收一次调用一次函数)
  99. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  100. {
  101. if(loadData==nil)
  102. {
  103. loadData=[[NSMutableData alloc]initWithCapacity:2048];
  104. }
  105. [loadData appendData:data];
  106. }
  107. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  108. {
  109. }
  110. -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
  111. {
  112. return cachedResponse;
  113. //    NSLog(@"将缓存输出");
  114. }
  115. -(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
  116. {
  117. //    NSLog(@"即将发送请求");
  118. return request;
  119. }
  120. //下载完成,将文件保存到沙河里面
  121. -(void)connectionDidFinishLoading:(NSURLConnection *)theConnection
  122. {
  123. UIApplication *app = [UIApplication sharedApplication];
  124. app.networkActivityIndicatorVisible = NO;
  125. //图片已经成功下载到本地缓存,指定图片
  126. if([loadData writeToFile:_fileName atomically:YES])
  127. {
  128. self.image = [UIImage imageWithContentsOfFile:_fileName];
  129. }
  130. connection = nil;
  131. loadData = nil;
  132. }
  133. //网络连接错误或者请求成功但是加载数据异常
  134. -(void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
  135. {
  136. UIApplication *app = [UIApplication sharedApplication];
  137. app.networkActivityIndicatorVisible = NO;
  138. //如果发生错误,则重新加载
  139. connection = nil;
  140. loadData = nil;
  141. [self loadImage];
  142. }
  143. -(void)dealloc
  144. {
  145. [_fileName release];
  146. [loadData release];
  147. [connection release];
  148. [_placeholderImage release];
  149. [_imageURL release];
  150. [super dealloc];
  151. }
  152. @end

上面的AsynImageView的.h和.m文件,就是所要实现的核心代码。如果想要调用AsynImageView,则只需执行如下代码即可:(需导入#import"AsynImageView.h")

[cpp] view plaincopy
  1. asynImgView = [[AsynImageView alloc] initWithFrame:CGRectMake(0, 5, 200, 100)];
  2. asynImgView.placeholderImage = [UIImage imageNamed:@"place.png"];
  3. asynImgView.imageURL = [NSString stringWithFormat:@"http://images.17173.com/2012/news/2012/10/10/lj1010sb10ds.jpg"];
  4. [self.view addSubView:asynImgView];

下面是我实现的UITableView异步加载图片的程序链接,就是上面的效果图的程序完整代码,大家可以参考一下:

http://download.csdn.net/detail/enuola/5112070

如有不恰当的地方,还望指点。

另外,图片的缓存可以定期进行清理,在此处没有写出清理代码,可以自行添加。

IOS中UITableView异步加载图片的实现相关推荐

  1. C#中PictureBox异步加载图片

    C#中PictureBox异步加载图片 ??yy 2017-11-05 23:30:00  443  收藏 版权 void Button1Click(object sender, EventArgs ...

  2. android 实现异步加载图片,Android中ImageView异步加载图片类

    本源码是从网络找到经修改以方便直接调用感觉用着还可以 首先在项目中添加一个专门加载图片的类AsyncImageLoaderpackage com.demo.core; import java.io.I ...

  3. Android之ListView异步加载图片且仅显示可见子项中的图片

    折腾了好多天,遇到 N 多让人崩溃无语的问题,不过今天终于有些收获了,这是实验的第一版,有些混乱,下一步进行改造细分,先把代码记录在这儿吧. 网上查了很多资料,发现都千篇一律,抄来抄去,很多细节和完整 ...

  4. 浅谈Android中的异步加载之ListView中图片的缓存及优化三

    隔了很久没写博客,现在必须快速脉动回来.今天我还是接着上一个多线程中的异步加载系列中的最后一个使用异步加载实现ListView中的图片缓存及其优化.具体来说这次是一个综合Demo.但是个人觉得里面还算 ...

  5. wemall app商城源码中基于JAVA的Android异步加载图片管理器代码

    wemall doraemon是Android客户端程序,服务端采用wemall微信商城,不对原商城做任何修改,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可随意定制修改.本文分享其中 ...

  6. LruCache缓存处理及异步加载图片类的封装

    Android中的缓存处理及异步加载图片类的封装   一.缓存介绍: (一).Android中缓存的必要性: 智能手机的缓存管理应用非常的普遍和需要,是提高用户体验的有效手段之一. 1.没有缓存的弊端 ...

  7. [置顶] 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅

    转载请注明出处http://blog.csdn.net/xiaanming/article/details/9825113 异步加载图片的例子,网上也比较多,大部分用了HashMap<Strin ...

  8. Android 开发笔记 ListView异步加载图片

    当ListView需要在线获取数据,并且列表中需要显示图片时,友好的处理方式是使用异步加载图片的方式. 这是因为LIstView中显示的内容是分为两部加载的,第一次加载文本信息(包含图片的uri地址) ...

  9. Android ListView异步加载图片乱序问题,原因分析及解决方案

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/45586553 在Android所有系统自带的控件当中,ListView这个控件算是 ...

最新文章

  1. 使用cmd将磁盘转化为GPT格式
  2. 指数基金日涨跌幅python_看懂巴菲特推荐的指数基金定投,Python验证
  3. 从零开始搭建 web 聊天室(一)
  4. [转载]poj 计算几何题全集(转)
  5. Direct2D教程(一)Direct2D已经来了,谁是GDI的终结者?
  6. iframe 覆盖父页面_一次iframe子页面与父页面的通信
  7. Android NDK开发入门学习笔记(图文教程,极其详尽)
  8. RPC和REST区别
  9. 30岁之前创业成功的12个要点
  10. shell练习DAY14
  11. 喜大普奔,VS Code 开启远程开发新时代!
  12. 使用Java反射(Reflect)、自定义注解(Customer Annotation)生成简单SQL语句
  13. 【以太坊开发】发币指南--进阶篇
  14. 在EnableQ创建一张问卷
  15. 功率曲线k值_锂电池放电曲线全面解析
  16. PPT制作基础知识(师从于珞珈老师)
  17. 生物细胞繁衍生存模拟仿真
  18. 计算机动画可分为二维和三维动画,二维动画与三维动画设计的区分
  19. Blender 置换生成地形模型
  20. TINA-TI导入SPICE模型(.TSM/.LIB/.SP1)

热门文章

  1. python的类型 变量 数值和字符串
  2. Android第二十期 - 微信的主体构架
  3. 为什么我从Python转战到Node.js
  4. linux下yum安装最新稳定版nginx
  5. JavaScript电话号码正则
  6. VS2015自定义类模板的方法
  7. Android使用 LruCache 缓存图片
  8. 开机报警disk boot sector is to be modified
  9. 【信息安全】职业发展之惑系列三 -- 我该选择怎样的职业发展道路
  10. C++ 出版公司(继承)