利用GCD实现图片本地缓存的方法

在网络请求中,若是用了ASI能够简单的实现缓存.缓存

但是若是使用的是AFNetworking,能够本身写一个实现缓存的方法.网络

简单来讲就是把图片URL进行MD5以后做为文件名保存到沙盒中.异步

 

首先在Cache.m中写个方法获取cacheDirectoryasync

+ (NSString*) cacheDirectory {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *cacheDirectory = [pathsobjectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"NXCaches"];
return cacheDirectory;
}

 

cacheTime是本地缓存失效的时间url

static NSTimeInterval cacheTime =  (double)604800;

 

经过key获取Object的方法,会先判断是否存在此文件.若是存在,还会判断文件是否过时spa

+ (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是在主线程哦)code

- (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;
});
});
}
}
相关文章
相关标签/搜索