iOS 缓存之(WebView)网页缓存

app中关于网页用的是越来越多了,所以有关网页缓存等问题就出现了?
怎么进行缓存,获取缓存的大小,获取缓存数据,清理缓存等问题就一个一个地出现了。针对这个问题,通过查找前人的博客简书等得到了答案,鉴于不是完整的解决方案,所以进行了整理,代码都是经过鄙人验证的,如有出入还请大家指正,谢谢!

1.先从存写起吧

/**
 * 网页缓存写入文件
 */
+ (void)writeToCache:(NSString *)fileName
{
    NSString *htmlResponseStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:fileName] encoding:NSUTF8StringEncoding error:nil];
    
    //创建文件管理器
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,      NSUserDomainMask, YES) objectAtIndex:0];
    
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"]withIntermediateDirectories:YES attributes:nil error:nil];
    
    //写入路径
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu",(unsigned long)[fileName hash]]];
    
    [htmlResponseStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

2.可以存了,那么怎么获取呢

/**
 * 获取网页缓存文件
 * fileName  文件名
 */
+ (NSString *)readFromCache:(NSString *)fileName{
    
    // 判断是否从缓存中获取
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu",(unsigned long)[fileName hash]]];
    
    NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    return htmlString;
}

3.那么缓存的大小是多少呢?

/**
 * 获取缓存文件大小
 */
+ (CGFloat)getCacheSize{
    
    //获取文件管理器对象
    NSFileManager * fileManger = [NSFileManager defaultManager];
    
    //获取缓存沙盒路径
    NSString * cachePath =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接缓存文件文件夹路径
    NSString * fileCachePath = [cachePath stringByAppendingPathComponent:@"/Caches"];
    
    //获取到该缓存目录下的所有子文件(只是文件名并不是路径,后面要拼接)
    NSArray * subFilePath = [fileManger subpathsAtPath:fileCachePath];
    
    //先定义一个缓存目录总大小的变量
    NSInteger fileTotalSize = 0;
    
    for (NSString * fileName in subFilePath)
    {
        //拼接文件全路径(注意:是文件)
        NSString * filePath = [fileCachePath stringByAppendingPathComponent:fileName];
        
        //获取文件属性
        NSDictionary * fileAttributes = [fileManger attributesOfItemAtPath:filePath error:nil];
        
        //根据文件属性判断是否是文件夹(如果是文件夹就跳过文件夹,不将文件夹大小累加到文件总大小)
        if ([fileAttributes[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
        
        //获取单个文件大小,并累加到总大小
        fileTotalSize += [fileAttributes[NSFileSize] integerValue];
    }
    
    //将字节大小转为MB,然后传出去
    return fileTotalSize/1024.0/1024.0;
}

4.是的,缓存要可以清除的

/**
 * 清除文件缓存
 */
+ (void)cleanCacheSuccess:(void (^)())success failure:(void (^)())failure{
    
    //获取文件管理器对象
    NSFileManager * fileManger = [NSFileManager defaultManager];
    
    //获取缓存沙盒路径
    NSString * cachePath =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接缓存文件文件夹路径
    NSString * fileCachePath = [cachePath stringByAppendingPathComponent:@"/Caches"];

    //获取到该缓存目录下的所有子文件(只是文件名并不是路径,后面要拼接)
    NSArray * subFilePath = [fileManger subpathsAtPath:fileCachePath];
    
    NSError *error = nil;
    for (NSString *p in subFilePath) {
        
        NSString *path = [fileCachePath stringByAppendingPathComponent:p];
        
        if ([fileManger fileExistsAtPath:path]) {
            
            [fileManger removeItemAtPath:path error:&error];
            
            if (error) {
                break;
            }
        }
    }
    
    if (error) {
        
        if (failure) failure();
        
    }else{
        
        if (success) success();
    }
}

5.为什么不写一个工具类呢,对啊,代码地址:https://github.com/silenceXz/WebCacheTool

如何使用小聊一下,下载代码并导入项目中,然后在使用的地方引入#import "CacheFileManagerTool.h"即可。

比如加载网页,需要知道网页地址self.urlPath,先判断是否有缓存,没有就进行网络加载并写入缓存,如果有就加载缓存文件。

NSURL *url = [NSURL URLWithString:self.urlPath];

// 如果有缓存,那么就从缓存中取得
NSString *htmlString = [CacheFileManagerTool readFromCache:self.urlPath];
if(!(htmlString == nil || [htmlString isEqualToString:@""])){
    
    [self.webHtml loadHTMLString:htmlString baseURL:url];
    
}else{
    
    [self.webHtml loadRequest:[NSURLRequest requestWithURL:url]];
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,556评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,255评论 4 61
  • 一辈子很长,一辈子也很短。谁都不知道在你预定的人生岁月中,会不会出现意外。当代人生活在电子产品,外卖,压...
    山下的白树林阅读 183评论 0 0
  • 获取当前的时间的秒数和微秒数本方法需要用到gettimeofday()函数,该函数需要引入的头文件是 sys/ti...
    胤默思佚阅读 193评论 0 0
  • 如果你爱我,请深爱 如果你不爱我,请不要伤害我 摩羯座的女生 没有暧昧这一说 喜欢便在一起 不喜欢就做陌生人了 如...
    我的酒窝超可爱的阅读 288评论 0 0