AFNetworking 图片的本地缓存问题

转载 2015年07月10日 12:47:09

原帖:http://blog.csdn.net/andy_jiangbin/article/details/17009157


ASI好久没更新,于是今天试了下AFNetWorking,调用图片请求方法很方便

    [self.imageViewsetImageWithURL:[NSURLURLWithString:@"http://best50.cn:8080/update/10/food/72.jpg"] placeholderImage:[UIImageimageNamed:@"placeholder.png"]];

      但发现个问题,程序重新启动后,图片还要重新请求,原来AFN用的是内存缓存图片机制,这能提高程序效率,但我们有时候,图片的本地缓存也是很重要的,于是,对AFN下UIImageView+AFNetworking.m文件的代码进行了修改,欢迎大家进行指正,修改和添加的方法如下:

复制代码
  1 - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 
  2               placeholderImage:(UIImage *)placeholderImage 
  3                        success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
  4                        failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
  5 {
  6     [self cancelImageRequestOperation];
  7 
  8     
  9     UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest];
 10     if (cachedImage) {
 11 
 12         self.image = cachedImage;
 13         self.af_imageRequestOperation = nil;
 14         
 15         if (success) {
 16             success(nil, nil, cachedImage);
 17         }
 18     } else {
 19         NSString *urlString = [[urlRequest URL] absoluteString];
 20         NSData *data = [self loadImageData:[self pathInCacheDirectory:@"WendaleCache"] imageName:[urlString md5]];
 21         if (data) {
 22             self.image = [UIImage imageWithData:data];
 23             self.af_imageRequestOperation = nil;
 24             
 25             if (success) {
 26                 success(nil, nil, self.image);
 27             }
 28             return;
 29         }
 30         
 31         self.image = placeholderImage;
 32         
 33         AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
 34         [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
 35             if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) {
 36                 if (success) {
 37                     success(operation.request, operation.response, responseObject);
 38                 }else if (responseObject) {

39 self.image = responseObject;}
 40                     //图片本地缓存
 41                 if ([self createDirInCache:@"WendaleCache"]) {
 42                     NSString *imageType = @"jpg";
 43                      //从url中获取图片类型
 44                   NSMutableArray *arr = (NSMutableArray *)[urlString componentsSeparatedByString:@"."];
 45                     if (arr) {
 46                          imageType = [arr objectAtIndex:arr.count-1];
 47                      }
 48                      [self saveImageToCacheDir:[self pathInCacheDirectory:@"WendaleCache"] image: responseObject imageName:[urlString md5] imageType:imageType];
 49                 }
 50                     
 51                     
 52  53                 
 54                 self.af_imageRequestOperation = nil;
 55             }
 56 
 57             [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
 58 
 59         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
 60             if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) {
 61                 if (failure) {
 62                     failure(operation.request, operation.response, error);
 63                 }
 64                 
 65                 self.af_imageRequestOperation = nil;
 66             }
 67         }];
 68         
 69         self.af_imageRequestOperation = requestOperation;
 70         
 71         [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
 72     }
 73 }
 74 
 75 -(NSString* )pathInCacheDirectory:(NSString *)fileName
 76 {
 77     NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
 78     NSString *cachePath = [cachePaths objectAtIndex:0];
 79     return [cachePath stringByAppendingPathComponent:fileName];
 80 }
 81 //创建缓存文件夹
 82 -(BOOL) createDirInCache:(NSString *)dirName
 83 {
 84     NSString *imageDir = [self pathInCacheDirectory:dirName];
 85     BOOL isDir = NO;
 86     NSFileManager *fileManager = [NSFileManager defaultManager];
 87     BOOL existed = [fileManager fileExistsAtPath:imageDir isDirectory:&isDir];
 88     BOOL isCreated = NO;
 89     if ( !(isDir == YES && existed == YES) )
 90     {
 91         isCreated = [fileManager createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
 92     }
 93     if (existed) {
 94         isCreated = YES;
 95     }
 96     return isCreated;
 97 }
 98 
 99 // 删除图片缓存
100 - (BOOL) deleteDirInCache:(NSString *)dirName
101 {
102     NSString *imageDir = [self pathInCacheDirectory:dirName];
103     BOOL isDir = NO;
104     NSFileManager *fileManager = [NSFileManager defaultManager];
105     BOOL existed = [fileManager fileExistsAtPath:imageDir isDirectory:&isDir];
106     bool isDeleted = false;
107     if ( isDir == YES && existed == YES )
108     {
109         isDeleted = [fileManager removeItemAtPath:imageDir error:nil];
110     }
111     
112     return isDeleted;
113 }
114 
115 // 图片本地缓存
116 - (BOOL) saveImageToCacheDir:(NSString *)directoryPath  image:(UIImage *)image imageName:(NSString *)imageName imageType:(NSString *)imageType
117 {
118     BOOL isDir = NO;
119     NSFileManager *fileManager = [NSFileManager defaultManager];
120     BOOL existed = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
121     bool isSaved = false;
122     if ( isDir == YES && existed == YES )
123     {
124         if ([[imageType lowercaseString] isEqualToString:@"png"])
125         {
126             isSaved = [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
127         }
128         else if ([[imageType lowercaseString] isEqualToString:@"jpg"] || [[imageType lowercaseString] isEqualToString:@"jpeg"])
129         {
130             isSaved = [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
131         }
132         else
133         {
134             NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", imageType);
135         }
136     }
137     return isSaved;
138 }
139 // 获取缓存图片
140 -(NSData*) loadImageData:(NSString *)directoryPath imageName:( NSString *)imageName
141 {
142     BOOL isDir = NO;
143     NSFileManager *fileManager = [NSFileManager defaultManager];
144     BOOL dirExisted = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
145     if ( isDir == YES && dirExisted == YES )
146     {
147         NSString *imagePath = [directoryPath stringByAppendingString : imageName];
148         BOOL fileExisted = [fileManager fileExistsAtPath:imagePath];
149         if (!fileExisted) {
150             return NULL;
151         }
152         NSData *imageData = [NSData dataWithContentsOfFile : imagePath];
153         return imageData;
154     }
155     else
156     {
157         return NULL;
158     }
159 }
复制代码


相关文章推荐

基于AFNetWorking3.0的图片缓存分析

文/Yasin的简书(简书作者) 原文链接:http://www.jianshu.com/p/b1045c3fc8d0 著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。 图片在APP中...

使用AFNetworking上传图片遇到的问题

1. The data couldn’t be read because it isn’t in the correct format 最近一个项目,在请求接口时,一直有问题,使用get请求可以...

iOS7使用AFNetworking3.0上传图片时出现的问题

文/挣扎在编码世界(简书作者) 原文链接:http://www.jianshu.com/p/0a3820d6a951 著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。 背景:在...

【Android】GridView显示大量图片缓存问题(一)

2012/10/23 15:22:27 | 阅读235次 前面有好几篇博客讨论到大量图片的存储以及缓存,比如:【Android】缩略图Thumbnails,【Android】图片的异...

JSP页面img图片缓存问题处理

JSP页面img图片缓存问题现象表述及问题解决 l  问题表述: 当对含有头像的客服人员信息进行修改(含对头像信息的修改)后,重新打开数据修改界面,发现文本内容修改成功,而头像内容仍然显示为原来的...

ios开发中关于图片缓存的问题整理

先说说缓存机制:   无缓存情况下:   对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的。      上面的情况会...

SDWebImage的实现机制以及解决tableView卡的问题和实现图片的缓存机制

SDWebImage的实现机制以及解决tableView卡的问题和实现图片的缓存机制

[Filter过滤器]解决缓存网站图片,css,js等问题

网站图片(gif,jpg等),css,js等不常改变的,可以考虑使用过滤器技术进行缓存 /*--------------------------XML---------------------*/ ...
  • gemman
  • gemman
  • 2013年03月22日 18:16
  • 975

sdwebimage缓存图片对比问题

开发IOS项目的时候,发现一个关于第三方框架sdwebimage的图片缓存的问题。搜了一下百度,发现有人已经提出同样的问题,如下: 有个问题请教一下各位,就是用sdwebimage下载图片的时候会...
  • lxubin
  • lxubin
  • 2015年05月10日 16:11
  • 15399
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:AFNetworking 图片的本地缓存问题
举报原因:
原因补充:

(最多只允许输入30个字)