iOS獲取App快取檔案的大小並清除快取
阿新 • • 發佈:2018-11-03
App在處理網路資源時,一般都會做離線快取處理,其中最典型離線快取框架為SDWebImage。
但是,離線快取會佔用一定的儲存空間,所以快取清理功能基本成為資訊、購物、閱讀類app的標配功能。
下面用程式碼來分別介紹快取檔案大小的獲取及清除快取。
快取檔案大小的獲取
我們可以新建一個工具類,並在類中定義一個類方法,宣告如下:
/** * 獲取資料夾尺寸 * @param directoryPath 資料夾路徑 * @param complete 計算完畢的Block回撥 */ + (void)getCacheSize:(NSString *)directoryPath complete:(void(^)(NSInteger))complete;
相應的實現如下:
+ (void)getCacheSize:(NSString *)directoryPath complete:(void(^)(NSInteger))complete { /* // 獲取caches 資料夾路徑 NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true) firstObject]; // 獲取default路徑 NSString *defaultPath = [cachePath stringByAppendingPathComponent:@"default"]; */ // 遍歷資料夾所有檔案,一個一個加起來 // 獲取檔案管理者 NSFileManager *mgr = [NSFileManager defaultManager]; // 判斷是否是資料夾 BOOL isDirectory; BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory]; if (!isDirectory || !isExist){ // 丟擲異常 name 異常名稱 reason報錯原因 NSException *excp =[NSException exceptionWithName:@"directory path error" reason:@"需要傳入的是存在的資料夾的路徑" userInfo:nil]; [excp raise]; }; // 開啟非同步 dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 獲取資料夾下所有的子路徑 包括子路徑的子路徑 NSArray *subPaths = [mgr subpathsAtPath:directoryPath]; NSInteger totalSize = 0; for (NSString *subPath in subPaths) { // 獲取到的檔案的全路徑 NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath]; // 忽略隱藏檔案 if([filePath containsString:@".DS"]) continue; // 判斷是否是資料夾 BOOL isDirectory; BOOL isExist = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory]; if(isDirectory || !isExist) continue; //獲取檔案屬性 attributesOfItemAtPath 只能回去檔案尺寸,獲取資料夾不對 NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil]; // default尺寸 NSInteger fileSize = [attr fileSize]; totalSize += fileSize; } NSLog(@"快取大小:%ld",totalSize); dispatch_sync(dispatch_get_main_queue(), ^{ //block回撥 if (complete) { complete(totalSize); } }); }); }
清除快取
方法的宣告
/**
* 清空快取
* @param directoryPath 資料夾路徑
*/
+ (void)removeCache:(NSString *)directoryPath;
方法的實現
+ (void)removeCache:(NSString *)directoryPath { // 清空快取cache中的所有資料夾 // 獲取檔案管理者 NSFileManager *mgr = [NSFileManager defaultManager]; BOOL isDirectory; BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory]; if (!isDirectory || !isExist){ // 丟擲異常 name 異常名稱 reason報錯原因 NSException *excp =[NSException exceptionWithName:@"directory path error" reason:@"需要傳入的是存在的資料夾的路徑" userInfo:nil]; [excp raise]; }; // 獲取資料夾下所有檔案。不包括子路徑的子路徑 NSArray *subPaths = [mgr contentsOfDirectoryAtPath:directoryPath error:nil]; for (NSString *subPath in subPaths) { // 拼接完整路徑 NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath]; // 刪除路徑 [mgr removeItemAtPath:filePath error:nil]; } }