tableview 图片异步加载

来源:互联网 发布:手机魔方软件 编辑:程序博客网 时间:2024/05/05 04:51

.h

#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;-(void)setImageURL:(NSString *)imageURL placeholder:(UIImage *)holder;@end

.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];                        self.image = _placeholderImage;    //指定默认图片    }    _placeholderImage = placeholderImage;}//重写imageURL的Setter方法-(void)setImageURL:(NSString *)imageURL placeholder:(UIImage *)holder{    if(imageURL != _imageURL)    {        self.image =holder;    //指定默认图片       [_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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    NSString *identifier =[NSString stringWithFormat:@"zc"];    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];    cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];    UILabel *lb =[[UILabel alloc]initWithFrame:CGRectMake(10, 190, 320, 180)];    lb.text =@"高原的广袤之地,优胜劣汰法则主导着这里所有生物的命运。2016年1月12日,中国地理景观大发现科学考察团队在路经位于西藏巴青县与丁青县交界的布加雪山冰川北坡途中,看到六只狗围着一只体型壮硕的孤狼对峙着。经过五六分钟的对峙交锋,狗一死一伤,受伤的狗一瘸一拐的和其它四只狗,丢下伙伴的尸体落荒而逃,而野狼毫不客气的叼起死狗往山顶而去。高原的广袤之地,优胜劣汰法则主导着这里所有生物的命运。2016年1月12日,中国地理景观大发现科学考察团队在路经位于西藏巴青县与丁青县交界的布加雪山冰川北坡途中,看到六只狗围着一只体型壮硕的孤狼对峙着。经过五六分钟的对峙交锋,狗一死一伤,受伤的狗一瘸一拐的和其它四只狗,丢下伙伴的尸体落荒而逃,而野狼毫不客气的叼起死狗往山顶而去。高原的广袤之地,优胜劣汰法则主导着这里所有生物的命运。2016年1月12日,中国地理景观大发现科学考察团队在路经位于西藏巴青县与丁青县交界的布加雪山冰川北坡途中,看到六只狗围着一只体型壮硕的孤狼对峙着。经过五六分钟的对峙交锋,狗一死一伤,受伤的狗一瘸一拐的和其它四只狗,丢下伙伴的尸体落荒而逃,而野狼毫不客气的叼起死狗往山顶而去。";    lb.numberOfLines =0;    [cell addSubview:lb];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        // 耗时的数据处理等        NSString *urlString = [NSString stringWithFormat:@"http://www.sd.xinhuanet.com/news/yule/2016-01/26/1117895557_14537752611851n.png"];        NSURL* url = [NSURL URLWithString:urlString];        NSData *imageData =[NSData dataWithContentsOfURL:url];        dispatch_async(dispatch_get_main_queue(), ^{            // 更新UI            UIImageView *view2 =[[UIImageView alloc]initWithFrame:CGRectMake(40, 20, 320, 180)];            view2.image =[UIImage imageWithData:imageData];            [cell addSubview:view2];        });      });        return cell;


0 0