IOS中UITableView异步加载图片的实现
生活随笔
收集整理的這篇文章主要介紹了
IOS中UITableView异步加载图片的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文轉載至 http://blog.csdn.net/enuola/article/details/8639404? 最近做一個項目,需要用到UITableView異步加載圖片的例子,看到網上有一個EGOImageView的很好的例子。 #import?<UIKit/UIKit.h>?? ?? @interface?AsynImageView?:?UIImageView?? {?? ????NSURLConnection?*connection;?? ????NSMutableData?*loadData;?? }?? //圖片對應的緩存在沙河中的路徑?? @property?(nonatomic,?retain)?NSString?*fileName;?? ?? //指定默認未加載時,顯示的默認圖片?? @property?(nonatomic,?retain)?UIImage?*placeholderImage;?? //請求網絡圖片的URL?? @property?(nonatomic,?retain)?NSString?*imageURL;?? ?? @end??
AsynImageView.m中的文件內容:#import?"AsynImageView.h"?? #import?<QuartzCore/QuartzCore.h>?? ?? @implementation?AsynImageView?? ?? @synthesize?imageURL?=?_imageURL;?? @synthesize?placeholderImage?=?_placeholderImage;?? ?? @synthesize?fileName?=?_fileName;?? ?? -?(id)initWithFrame:(CGRect)frame?? {?? ????self?=?[super?initWithFrame:frame];?? ????if?(self)?{?? ????????//?Initialization?code?? ?? ????????self.layer.borderColor?=?[[UIColor?whiteColor]?CGColor];?? ????????self.layer.borderWidth?=?2.0;?? ????????self.backgroundColor?=?[UIColor?grayColor];?? ?????????? ????}?? ????return?self;?? }?? ?? //重寫placeholderImage的Setter方法?? -(void)setPlaceholderImage:(UIImage?*)placeholderImage?? {?? ????if(placeholderImage?!=?_placeholderImage)?? ????{?? ????????[_placeholderImage?release];?? ?????????? ????????_placeholderImage?=?placeholderImage;?? ????????self.image?=?_placeholderImage;????//指定默認圖片?? ????}?? }?? ?? //重寫imageURL的Setter方法?? -(void)setImageURL:(NSString?*)imageURL?? {?? ????if(imageURL?!=?_imageURL)?? ????{?? ????????self.image?=?_placeholderImage;????//指定默認圖片?? ???????[_imageURL?release];?? ????????_imageURL?=?[imageURL?retain];?? ????}?? ?????? ????if(self.imageURL)?? ????{?? ????????//確定圖片的緩存地址?? ????????NSArray?*path=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,?NSUserDomainMask,?YES);?? ????????NSString?*docDir=[path?objectAtIndex:0];?? ????????NSString?*tmpPath=[docDir?stringByAppendingPathComponent:@"AsynImage"];?? ?????????? ????????NSFileManager?*fm?=?[NSFileManager?defaultManager];?? ????????if(![fm?fileExistsAtPath:tmpPath])?? ????????{?? ????????????[fm?createDirectoryAtPath:tmpPath?withIntermediateDirectories:YES?attributes:nil?error:nil];?? ????????}?? ????????NSArray?*lineArray?=?[self.imageURL?componentsSeparatedByString:@"/"];?? ????????self.fileName?=?[NSString?stringWithFormat:@"%@/%@",?tmpPath,?[lineArray?objectAtIndex:[lineArray?count]?-?1]];?? ?????????? ????????//判斷圖片是否已經下載過,如果已經下載到本地緩存,則不用重新下載。如果沒有,請求網絡進行下載。?? ????????if(![[NSFileManager?defaultManager]?fileExistsAtPath:_fileName])?? ????????{?? ????????????//下載圖片,保存到本地緩存中?? ????????????[self?loadImage];?? ????????}?? ????????else?? ????????{?? ????????????//本地緩存中已經存在,直接指定請求的網絡圖片?? ????????????self.image?=?[UIImage?imageWithContentsOfFile:_fileName];?? ????????}?? ????}?? }?? ?? //網絡請求圖片,緩存到本地沙河中?? -(void)loadImage?? {?? ????//對路徑進行編碼?? ????@try?{?? ????????//請求圖片的下載路徑?? ????????//定義一個緩存cache?? ????????NSURLCache?*urlCache?=?[NSURLCache?sharedURLCache];?? ????????/*設置緩存大小為1M*/?? ????????[urlCache?setMemoryCapacity:1*124*1024];?? ?????????? ????????//設子請求超時時間為30s?? ????????NSMutableURLRequest?*request?=?[NSMutableURLRequest?requestWithURL:[NSURL?URLWithString:self.imageURL]?cachePolicy:NSURLRequestReloadIgnoringCacheData?timeoutInterval:60.0];?? ?????????? ????????//從請求中獲取緩存輸出?? ????????NSCachedURLResponse?*response?=?[urlCache?cachedResponseForRequest:request];?? ????????if(response?!=?nil)?? ????????{?? ????????????//????????????NSLog(@"如果又緩存輸出,從緩存中獲取數據");?? ????????????[request?setCachePolicy:NSURLRequestReturnCacheDataDontLoad];?? ????????}?? ?????????? ????????/*創建NSURLConnection*/?? ????????if(!connection)?? ????????????connection?=?[[NSURLConnection?alloc]?initWithRequest:request?delegate:self?startImmediately:YES];?? ????????//開啟一個runloop,使它始終處于運行狀態?? ?????????? ????????UIApplication?*app?=?[UIApplication?sharedApplication];?? ????????app.networkActivityIndicatorVisible?=?YES;?? ?? ????????[[NSRunLoop?currentRunLoop]?runMode:NSDefaultRunLoopMode?beforeDate:[NSDate?distantFuture]];?? ?????????? ????}?? ????@catch?(NSException?*exception)?{?? ????????//????????NSLog(@"沒有相關資源或者網絡異常");?? ????}?? ????@finally?{?? ????????;//.....?? ????}?? }?? ?? #pragma?mark?-?NSURLConnection?Delegate?Methods?? //請求成功,且接收數據(每接收一次調用一次函數)?? -(void)connection:(NSURLConnection?*)connection?didReceiveData:(NSData?*)data?? {?? ????if(loadData==nil)?? ????{?? ????????loadData=[[NSMutableData?alloc]initWithCapacity:2048];?? ????}?? ????[loadData?appendData:data];?? }?? ?? -(void)connection:(NSURLConnection?*)connection?didReceiveResponse:(NSURLResponse?*)response?? {?? ?????? }?? ?? -(NSCachedURLResponse?*)connection:(NSURLConnection?*)connection?willCacheResponse:(NSCachedURLResponse?*)cachedResponse?? {?? ????return?cachedResponse;?? ????//????NSLog(@"將緩存輸出");?? }?? ?? -(NSURLRequest?*)connection:(NSURLConnection?*)connection?willSendRequest:(NSURLRequest?*)request?redirectResponse:(NSURLResponse?*)response?? {?? ????//????NSLog(@"即將發送請求");?? ????return?request;?? }?? //下載完成,將文件保存到沙河里面?? -(void)connectionDidFinishLoading:(NSURLConnection?*)theConnection?? {?? ????UIApplication?*app?=?[UIApplication?sharedApplication];?? ????app.networkActivityIndicatorVisible?=?NO;?? ?????? ????//圖片已經成功下載到本地緩存,指定圖片?? ????if([loadData?writeToFile:_fileName?atomically:YES])?? ????{?? ????????self.image?=?[UIImage?imageWithContentsOfFile:_fileName];?? ????}?? ?? ????connection?=?nil;?? ????loadData?=?nil;?? ?????? }?? //網絡連接錯誤或者請求成功但是加載數據異常?? -(void)connection:(NSURLConnection?*)theConnection?didFailWithError:(NSError?*)error?? {?? ????UIApplication?*app?=?[UIApplication?sharedApplication];?? ????app.networkActivityIndicatorVisible?=?NO;?? ?????? ????//如果發生錯誤,則重新加載?? ????connection?=?nil;?? ????loadData?=?nil;?? ????[self?loadImage];?? }?? ?? -(void)dealloc?? {?? ????[_fileName?release];?? ????[loadData?release];?? ????[connection?release];?? ?????? ????[_placeholderImage?release];?? ????[_imageURL?release];?? ?????? ????[super?dealloc];?? }?? ?? @end??
上面的AsynImageView的.h和.m文件,就是所要實現的核心代碼。如果想要調用AsynImageView,則只需執行如下代碼即可:(需導入#import"AsynImageView.h")asynImgView?=?[[AsynImageView?alloc]?initWithFrame:CGRectMake(0,?5,?200,?100)];?? ????????asynImgView.placeholderImage?=?[UIImage?imageNamed:@"place.png"];?? ????????asynImgView.imageURL?=?[NSString?stringWithFormat:@"http://images.17173.com/2012/news/2012/10/10/lj1010sb10ds.jpg"];?? ????????[self.view?addSubView:asynImgView];??
但是由于,EGOImageView的實現比較復雜,于是自己就動手做了一個AsynImageView,同樣可以實現EGOImageView的效果。
而且自己寫的代碼比較清晰,容易理解,同樣可以實現指定placehoderImage以及指定imageURL,來進行圖片的異步加載。
同時,如果圖片已經請求過,則不會再重復請求網絡,會直接讀取本地緩存文件。
效果如下:
具體實現思路如下:
?
?AsynImageView.h的文件內容:
?
[cpp]?view plaincopyAsynImageView.m中的文件內容:
?
?
[cpp]?view plaincopy上面的AsynImageView的.h和.m文件,就是所要實現的核心代碼。如果想要調用AsynImageView,則只需執行如下代碼即可:(需導入#import"AsynImageView.h")
?
?
[cpp]?view plaincopy?
下面是我實現的UITableView異步加載圖片的程序鏈接,就是上面的效果圖的程序完整代碼,大家可以參考一下:
http://download.csdn.net/detail/enuola/5112070
如有不恰當的地方,還望指點。
另外,圖片的緩存可以定期進行清理,在此處沒有寫出清理代碼,可以自行添加。
?
總結
以上是生活随笔為你收集整理的IOS中UITableView异步加载图片的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Golang 学习笔记(安装)
- 下一篇: 超微服务器使用IPMI安装操作系统小记