標籤:link ice share float sof ios att pre long
行動裝置 App在處理網路資源時,一般都會做離線緩衝處理,其中以圖片緩衝最為典型,其中很流行的離線緩衝架構為SDWebImage。
但是,離線緩衝會佔用手機儲存空間,所以緩衝清理功能基本成為資訊、購物、閱讀類app的標配功能。
今天介紹的離線緩衝功能的實現,主要分為快取檔案大小的擷取、刪除快取檔案的實現。
擷取快取檔案的大小
由於快取檔案存在沙箱中,我們可以通過NSFileManager API來實現對快取檔案大小的計算。
計算單個檔案大小
+(float)fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if([fileManager fileExistsAtPath:path]){ long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize; return size/1024.0/1024.0; } return 0;}
計算目錄大小
+(float)folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; float folderSize; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; folderSize +=[FileService fileSizeAtPath:absolutePath]; } //SDWebImage架構自身計算緩衝的實現 folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0; return folderSize; } return 0;}
清理快取檔案
同樣也是利用NSFileManager API進行檔案操作,SDWebImage架構自己實現了清理快取作業,我們可以直接調用。
+(void)clearCache:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { //如有需要,加入條件,過濾掉不想刪除的檔案 NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; [fileManager removeItemAtPath:absolutePath error:nil]; } } [[SDImageCache sharedImageCache] cleanDisk];}
實現效果:
iOS開發-清理緩衝功能的實現