在网络请求中,如果用了ASI可以简单的实现缓存.
可是如果使用的是AFNetworking,可以自己写一个实现缓存的方法.
简单来说就是把图片URL进行MD5之后作为文件名保存到沙盒中.
首先在Cache.m中写个方法获取cacheDirectory
+ (NSString*) cacheDirectory {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *cacheDirectory = [pathsobjectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"NXCaches"];
return cacheDirectory;
}
cacheTime是本地缓存失效的时间
static NSTimeInterval cacheTime = (double)604800;
通过key获取Object的方法,会先判断是否存在此文件.如果存在,还会判断文件是否过期
+ (NSData*) objectForKey:(NSString*)key {
NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSString *filename = [self.cacheDirectorystringByAppendingPathComponent:key];
if ([fileManager fileExistsAtPath:filename])
{
NSDate *modificationDate = [[fileManagerattributesOfItemAtPath:filename error:nil]objectForKey:NSFileModificationDate];
if ([modificationDatetimeIntervalSinceNow] > cacheTime) {
[fileManager removeItemAtPath:filename error:nil];
} else {
NSData *data = [NSDatadataWithContentsOfFile:filename];
return data;
}
}
return nil;
}
保存Object的方法.先判断是否存在缓存文件夹,如果不存在,创建.
+ (void) setObject:(NSData*)data forKey:(NSString*)key {
NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSString *filename = [self.cacheDirectorystringByAppendingPathComponent:key];
BOOL isDir = YES;
if (![fileManager fileExistsAtPath:self.cacheDirectoryisDirectory:&isDir]) {
[fileManager createDirectoryAtPath:self.cacheDirectorywithIntermediateDirectories:NOattributes:nilerror:nil];
}
NSError *error;
@try {
[data writeToFile:filenameoptions:NSDataWritingAtomic error:&error];
}
@catch (NSException * e) {
//TODO: error handling maybe
}
}
在通过url读取图片时使用下面方法,判断本地如果有图片数据就从本地读取,否则通过异步请求获取(注意,刷新UI是在主线程哦)
- (void) loadImageFromURL:(NSString*)URL {
NSURL *imageURL = [NSURLURLWithString:URL];
NSString *key = [URL MD5Hash];
NSData *data = [FTWCacheobjectForKey:key];
if (data) {
UIImage *image = [UIImageimageWithData:data];
imageView.image = image;
} else {
imageView.image = [UIImageimageNamed:@"img_def"];
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0ul);
dispatch_async(queue, ^{
NSData *data = [NSDatadataWithContentsOfURL:imageURL];
[FTWCachesetObject:data forKey:key];
UIImage *image = [UIImageimageWithData:data];
dispatch_sync(dispatch_get_main_queue(), ^{
imageView.image = image;
});
});
}
}