分享

IOS中UITableView异步加载图片的实现

 ccccshq 2014-06-26

最近做一个项目,需要用到UITableView异步加载图片的例子,看到网上有一个EGOImageView的很好的例子。

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

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

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

效果如下:

异步加载图片效果图片异步加载 效果

具体实现思路如下:

 AsynImageView.h的文件内容:

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

AsynImageView.m中的文件内容:

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

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

  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

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

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多