利用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;
});
});
}
}
相關文章
相關標籤/搜索