平常大多用SDWebimage做圖片的緩存,如果做語(yǔ)音聊天SDWebimage就不太夠用
,所以推薦用EGOCache做文件緩存。
EGOCache采用磁盤(pán)存儲(chǔ)方式存儲(chǔ),如果文件使用頻率很高可以緩存到內(nèi)存中,減少io操作。
1.EGOCache 作用
EGOCache可以緩存實(shí)現(xiàn)了<NSCodeing>協(xié)議的對(duì)象、圖片、語(yǔ)音、plist文件
2.EGOCache 安裝
pod 'EGOCache', '~> 2.1.3'
3.EGOCache 使用
/**
* 創(chuàng)建緩存目錄
*
* @return 緩存目錄
*/
-(NSString *)createCacheDirection
{
//沙盒目錄
NSLog(@"-----%@",NSHomeDirectory());
//Document 文件夾目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathDocuments = [paths objectAtIndex:0];
//創(chuàng)建緩存目錄
NSString *createPath = [NSString stringWithFormat:@"%@/MessageCache", pathDocuments];
// 判斷文件夾是否存在,如果不存在,則創(chuàng)建
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];
如果不指定緩存路徑,默認(rèn)緩存到library下的cache目錄下
//清除緩存
[egocache clearCache];
//設(shè)置緩存時(shí)間 默認(rèn)時(shí)間一天 一天的時(shí)間表示:24*60*60
egocache.defaultTimeoutInterval = 60;
緩存文字
//緩存文字
NSString *cacheString = @"111111111111";
[egocache setString:cacheString forKey:@"string"];
//是否有這個(gè)緩存
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) {
//此處已經(jīng)在主線(xiàn)程了
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
//拿到圖片后緩存起來(lái)
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];
});
}];
//開(kāi)始任務(wù)
[downloadTask resume];
}
讀取圖片
//是否有這個(gè)緩存
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時(shí)遍歷一下當(dāng)前文件日期是否超過(guò)當(dāng)前日期,如果超過(guò)刪除文件
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];

緩存記錄的plist文件

在沙盒中的樣子