EGOCache 的简单使用

11 篇文章 0 订阅

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];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值