这个是自己写的图片下载及缓存方法。下面只贴代码了。CSDN传文件不会。
还是那句话:有不懂的可以加入群交流:QQ群:28433020 交流
1.引用
#import "OperationsOfImagesToWaterFall.h"//个人写的图片下载2.
//引入 委托 <OperationsOfImagesToWaterFallDelegate> OperationsOfImagesToWaterFall *_operationDownload;
3.初始化
- (void)viewDidLoad { [super viewDidLoad]; _operationDownload = [[OperationsOfImagesToWaterFall alloc] initWithDirectoryOfCache:@"cachesOfImage"];//初始化并创建缓存目录 [_operationDownload setDelegate:self]; }
这里面有delegate 根据需要 我还加入block的使用。
block的使用
需要注意的是:如果要在block里面修改变量,记得使用修饰词
__block
//调用下载并使用block [operationOfImagesDown SetDownLoadImageWithUrl:photo withSuccessBlock:^(UIImage *image) { if (image) { //这个就是下载后得到的图片,可以去做其他的事情 } } }];
OperationsOfImagesToWaterFall.h
// // OperationsOfImagesToWaterFall.h // YunKuang // // Created by icash on 12-11-1. // Copyright (c) 2012年 icash All rights reserved. // #import <Foundation/Foundation.h> #import "ASIHTTPRequest.h" #if NS_BLOCKS_AVAILABLE typedef void(^ImageDownSuccessBlock)(UIImage *image); //typedef void(^ImageDownFailureBlock)(NSError *error); #endif @protocol OperationsOfImagesToWaterFallDelegate; @interface OperationsOfImagesToWaterFall : NSObject{ id <OperationsOfImagesToWaterFallDelegate> _delegate; NSMutableSet *_ImagesInLoading;//正在加载的图片 NSMutableSet *_ImagesInCompleted;//加载完成的图片 NSOperationQueue *_operationQueue;//执行队列 NSString *_filePath; NSFileManager *_fileManger; BOOL PathExits; } @property (nonatomic, assign) id <OperationsOfImagesToWaterFallDelegate> delegate; @property (nonatomic, retain) NSString *filePath; - (void)SetDownLoadImageWithUrl:(NSString *)URL;//初始 - (void)SetDownLoadImageWithUrl:(NSString *)URL withSuccessBlock:(ImageDownSuccessBlock)success;//有block的 - (void)CancelDownLoad;//停止下载 - (id)initWithDirectoryOfCache:(NSString *)directory; //缓存操作 - (void)FileOfWriteWithArray:(NSArray *)array;//写操作 - (UIImage *)FileOfReadWithUrl:(NSString *)URL;//读操作 @end //实现在的代理方法 @protocol OperationsOfImagesToWaterFallDelegate <NSObject> - (void) ImagesOfWaterFallDidDownloadSuccess:(UIImage *)image URL:(NSString *)URL; - (void) ImagesOfWaterFallDidDownloadFailed:(NSString *)URL; @end
OperationsOfImagesToWaterFall.m
// // OperationsOfImagesToWaterFall.m // YunKuang // // Created by icash on 12-11-1. // Copyright (c) 2012年 icash All rights reserved. // #import "OperationsOfImagesToWaterFall.h" @implementation OperationsOfImagesToWaterFall @synthesize delegate = _delegate; @synthesize filePath = _filePath; - (id)init { if (self =[super init]) { printf("it had init"); _operationQueue = [[NSOperationQueue alloc]init]; [_operationQueue setMaxConcurrentOperationCount:1]; _ImagesInLoading = [[NSMutableSet alloc]init]; _ImagesInCompleted = [[NSMutableSet alloc]init]; } return self; } //初始化管理器,返回是否该目录存在 - (BOOL)initFileManager:(NSString *)dic { _fileManger = [NSFileManager defaultManager]; NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachePath = [cache objectAtIndex:0]; self.filePath = [cachePath stringByAppendingString:@"/"]; self.filePath = [_filePath stringByAppendingString:dic];// 目录 BOOL k; if (![_fileManger fileExistsAtPath:_filePath]) { k = [_fileManger createDirectoryAtPath: _filePath withIntermediateDirectories:YES attributes:nil error:nil];//创建目录 //创建失败K就是NO,成功K就是YES; }else { k = YES; } NSLog(@"k===%d===\n\n",k); return k; } - (id)initWithDirectoryOfCache:(NSString *)directory { [self init]; if (self =[super init]) { PathExits = [self initFileManager:directory];//初始化管理器,返回是否该目录存在 } return self; } //初始 - (void)SetDownLoadImageWithUrl:(NSString *)URL { [self SetDownLoadImageWithUrl:URL withSuccessBlock:Nil]; } - (void)SetDownLoadImageWithUrl:(NSString *)URL withSuccessBlock:(ImageDownSuccessBlock)success { UIImage *image00 = nil; image00 = [self FileOfReadWithUrl:URL];//从缓存读取 if (image00) {//如果有这个文件了 [_ImagesInCompleted addObject:URL]; if (_delegate != nil && [_delegate respondsToSelector:@selector(ImagesOfWaterFallDidDownloadSuccess:URL:)] && image00) { [_delegate ImagesOfWaterFallDidDownloadSuccess:image00 URL:URL]; } success(image00);//更新block }else {//缓存中没有这个文件 if (![_ImagesInLoading containsObject:URL] && ![_ImagesInCompleted containsObject:URL]) {//不包含 [_ImagesInLoading addObject:URL];//添加URL dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *avatarImage = nil; NSURL *url = [NSURL URLWithString:URL]; NSData *responseData = [NSData dataWithContentsOfURL:url]; avatarImage = [UIImage imageWithData:responseData]; if (avatarImage) { success(avatarImage);//更新block NSArray *array = [[NSArray alloc] initWithObjects:URL,responseData, success,nil]; [self performSelectorInBackground:@selector(FileOfWriteWithArray:) withObject:array]; array = nil; [array release]; if (_delegate != nil && [_delegate respondsToSelector:@selector(ImagesOfWaterFallDidDownloadSuccess:URL:)]) { [_delegate ImagesOfWaterFallDidDownloadSuccess:avatarImage URL:URL]; } } else { if (_delegate != nil && [_delegate respondsToSelector:@selector(ImagesOfWaterFallDidDownloadFailed:)]) { [_delegate ImagesOfWaterFallDidDownloadFailed:URL]; } } }); }else{//可能有缓存 UIImage *image2 = [self FileOfReadWithUrl:URL];//从缓存读取 if (image2) { if (_delegate != nil && [_delegate respondsToSelector:@selector(ImagesOfWaterFallDidDownloadSuccess:URL:)] && image2) { [_delegate ImagesOfWaterFallDidDownloadSuccess:image2 URL:URL]; } success(image2);//更新block }else{ if (_delegate != nil && [_delegate respondsToSelector:@selector(ImagesOfWaterFallDidDownloadFailed:)]) { [_delegate ImagesOfWaterFallDidDownloadFailed:URL]; } } } } } //写图片 - (void)FileOfWriteWithArray:(NSArray *)array { NSString *url = (NSString *)[array objectAtIndex:0]; NSData *data = (NSData *)[array objectAtIndex:1]; NSString *fileName = [NSString stringWithFormat:@"%@",[[url componentsSeparatedByString:@"/"] lastObject]]; NSString *file = [_filePath stringByAppendingFormat:@"/%@",fileName]; if ([data writeToFile:file atomically:YES]){ [_ImagesInCompleted addObject:url]; [_ImagesInLoading removeObject:url]; ImageDownSuccessBlock succ = [array objectAtIndex:2]; succ([UIImage imageWithData:data]); // NSLog(@"file==%@=写文件成功",file); } else { // NSLog(@"file==%@=写文件失败",file); } } //读操作 - (UIImage *)FileOfReadWithUrl:(NSString *)URL { NSString *fileName = [NSString stringWithFormat:@"%@",[[URL componentsSeparatedByString:@"/"] lastObject]]; NSString *file = [_filePath stringByAppendingFormat:@"/%@",fileName]; UIImage *image1 = nil; if ([_fileManger fileExistsAtPath:file]) { image1 = [UIImage imageWithContentsOfFile:file]; } return image1; } //停止下载 - (void)CancelDownLoad { [_operationQueue cancelAllOperations]; } - (void) dealloc { [_operationQueue release]; [_ImagesInCompleted release]; [_ImagesInLoading release]; // Block_release(ImageDownSuccessBlock); [super dealloc]; } @end