平常大多用SDWebimage做图片的缓存,如果做语音聊天SDWebimage就不太够用
,所以推荐用EGOCache做文件缓存。
EGOCache采用磁盘存储方式存储,如果文件使用频率很高可以缓存到内存中,减少io操作。
1.EGOCache 作用
EGOCache可以缓存实现了<NSCodeing>协议的对象、图片、语音、plist文件
2.EGOCache 安装
pod 'EGOCache', '~> 2.1.3'
3.EGOCache 使用
/**
* 创建缓存目录
*
* @return 缓存目录
*/
-(NSString *)createCacheDirection
{
//沙盒目录
NSLog(@"-----%@",NSHomeDirectory());
//Document 文件夹目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathDocuments = [paths objectAtIndex:0];
//创建缓存目录
NSString *createPath = [NSString stringWithFormat:@"%@/MessageCache", pathDocuments];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
BOOL result = [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
if (result) {
return createPath;
}else
{
return nil;
}
} else {
NSLog(@"FileDir is exists.");
return createPath;
}
}
初始化缓存
//initWithCacheDirectory 指定缓存目录
EGOCache *egocache = [[EGOCache globalCache] initWithCacheDirectory:cacheDirectory];
如果不指定缓存路径,默认缓存到library下的cache目录下
//清除缓存
[egocache clearCache];
//设置缓存时间 默认时间一天 一天的时间表示:24*60*60
egocache.defaultTimeoutInterval = 60;
缓存文字
//缓存文字
NSString *cacheString = @"111111111111";
[egocache setString:cacheString forKey:@"string"];
//是否有这个缓存
BOOL ishaveCacheFile = [egocache hasCacheForKey:@"string"];
if (ishaveCacheFile) {
//读取文字
NSString *currentCacheString = [egocache stringForKey:@"string"];
NSLog(@"缓存的文字:%@",currentCacheString);
}
缓存图片
先下载图片
-(void)downloadFileWithURLString:(NSString *)aURLString withFileName:(NSString *)aCacheName
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:aURLString]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//此处已经在主线程了
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
//拿到图片后缓存起来
EGOCache *egocache = [EGOCache globalCache];
[egocache setImage:image forKey:aCacheName];
dispatch_async(dispatch_get_main_queue(), ^{
int a = [[aCacheName stringByReplacingOccurrencesOfString:@"cache_" withString:@""] intValue];
CGFloat image_width = 10;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(a*image_width, a*image_width, image_width, image_width)];
EGOCache *egocache = [EGOCache globalCache];
imageView.image = [egocache imageForKey:aCacheName];
[self.view addSubview:imageView];
});
}];
//开始任务
[downloadTask resume];
}
读取图片
//是否有这个缓存
BOOL ishaveCacheImage = [egocache hasCacheForKey:@"cache_0"];
if (ishaveCacheImage) {
//读取图片
UIImage *currentCacheimage = [egocache imageForKey:@"cache_0"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:currentCacheimage];
imageView.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:imageView];
imageView.tag = 10010;
}
清除缓存原理
//每次初始化EGOCache时遍历一下当前文件日期是否超过当前日期,如果超过删除文件
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
NSMutableArray* removedKeys = [[NSMutableArray alloc] init];
for(NSString* key in _cacheInfo) {
if([_cacheInfo[key] timeIntervalSinceReferenceDate] <= now) {
[[NSFileManager defaultManager] removeItemAtPath:cachePathForKey(_directory, key) error:NULL];
[removedKeys addObject:key];
}
}
[_cacheInfo removeObjectsForKeys:removedKeys];