AFNetworking 图片的本地缓存问题

  更新2013年04月02日11:46:36:修改了用 [imageView setImageWithURLRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@""]] placeholderImage:[UIImageimageNamed:@"loader.jpg"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {    }];图片不能缓存的问题

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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 }

 

posted @ 2013-01-17 14:42  七夜小魔军  阅读(4862)  评论(5编辑  收藏  举报