iOS 緩存之(WebView)網(wǎng)頁緩存

app中關(guān)于網(wǎng)頁用的是越來越多了,所以有關(guān)網(wǎng)頁緩存等問題就出現(xiàn)了?
怎么進(jìn)行緩存,獲取緩存的大小,獲取緩存數(shù)據(jù),清理緩存等問題就一個一個地出現(xiàn)了。針對這個問題,通過查找前人的博客簡書等得到了答案,鑒于不是完整的解決方案,所以進(jìn)行了整理,代碼都是經(jīng)過鄙人驗證的,如有出入還請大家指正,謝謝!

1.先從存寫起吧

/**
 * 網(wǎng)頁緩存寫入文件
 */
+ (void)writeToCache:(NSString *)fileName
{
    NSString *htmlResponseStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:fileName] encoding:NSUTF8StringEncoding error:nil];
    
    //創(chuàng)建文件管理器
    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.可以存了,那么怎么獲取呢

/**
 * 獲取網(wǎng)頁緩存文件
 * 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];
        
        //根據(jù)文件屬性判斷是否是文件夾(如果是文件夾就跳過文件夾,不將文件夾大小累加到文件總大?。?        if ([fileAttributes[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
        
        //獲取單個文件大小,并累加到總大小
        fileTotalSize += [fileAttributes[NSFileSize] integerValue];
    }
    
    //將字節(jié)大小轉(zhuǎn)為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

如何使用小聊一下,下載代碼并導(dǎo)入項目中,然后在使用的地方引入#import "CacheFileManagerTool.h"即可。

比如加載網(wǎng)頁,需要知道網(wǎng)頁地址self.urlPath,先判斷是否有緩存,沒有就進(jìn)行網(wǎng)絡(luò)加載并寫入緩存,如果有就加載緩存文件。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,234評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,447評論 4 61
  • 一輩子很長,一輩子也很短。誰都不知道在你預(yù)定的人生歲月中,會不會出現(xiàn)意外。當(dāng)代人生活在電子產(chǎn)品,外賣,壓...
    山下的白樹林閱讀 203評論 0 0
  • 獲取當(dāng)前的時間的秒數(shù)和微秒數(shù)本方法需要用到gettimeofday()函數(shù),該函數(shù)需要引入的頭文件是 sys/ti...
    胤默思佚閱讀 219評論 0 0
  • 如果你愛我,請深愛 如果你不愛我,請不要傷害我 摩羯座的女生 沒有曖昧這一說 喜歡便在一起 不喜歡就做陌生人了 如...
    我的酒窩超可愛的閱讀 313評論 0 0

友情鏈接更多精彩內(nèi)容