#import <Foundation/Foundation.h>
@interface SPClearCacheTool : NSObject
/**
* 獲取緩存大小
*/
+ (NSString *)getCacheSize;
/**
* 清理緩存
*/
+ (BOOL)clearCaches;
@end
#import "SPClearCacheTool.h"
#define fileManager [NSFileManager defaultManager]
#define cachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
@implementation SPClearCacheTool
// 獲取cachePath路徑下文件夾大小
+ (NSString *)getCacheSize {
// 調試
#ifdef DEBUG
// 如果文件夾不存在或者不是一個文件夾那么就拋出一個異常
// 拋出異常會導致程序閃退,所以只在調試階段拋出,發布階段不要再拋了,不然極度影響用戶體驗
BOOL isDirectory = NO;
BOOL isExist = [fileManager fileExistsAtPath:cachePath isDirectory:&isDirectory];
if (!isExist || !isDirectory) {
NSException *exception = [NSException exceptionWithName:@"文件錯誤" reason:@"請檢查你的文件路徑!" userInfo:nil];
[exception raise];
}
//發布
#else
#endif
//獲取“cachePath”文件夾下面的所有文件
NSArray *subpathArray= [fileManager subpathsAtPath:cachePath];
NSString *filePath = nil;
long long totalSize = 0;
for (NSString *subpath in subpathArray) {
// 拼接每一個文件的全路徑
filePath =[cachePath stringByAppendingPathComponent:subpath];
// isDirectory,是否是文件夾,默認不是
BOOL isDirectory = NO;
// isExist,判斷文件是否存在
BOOL isExist = [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
// 文件不存在,是文件夾,是隱藏文件都過濾
if (!isExist || isDirectory || [filePath containsString:@".DS"]) continue;
// attributesOfItemAtPath 只可以獲得文件屬性,不可以獲得文件夾屬性,這個也就是需要遍歷文件夾里面每一個文件的原因
long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
totalSize += fileSize;
}
// 將文件夾大小轉換為 M/KB/B
NSString *totalSizeString = nil;
if (totalSize > 1000 * 1000) {
totalSizeString = [NSString stringWithFormat:@"%.1fM",totalSize / 1000.0f /1000.0f];
} else if (totalSize > 1000) {
totalSizeString = [NSString stringWithFormat:@"%.1fKB",totalSize / 1000.0f ];
} else {
totalSizeString = [NSString stringWithFormat:@"%.1fB",totalSize / 1.0f];
}
return totalSizeString;
}
// 清除cachePath文件夾下緩存大小
+ (BOOL)clearCaches {
// 拿到cachePath路徑的下一級目錄的子文件夾
// contentsOfDirectoryAtPath:error:遞歸
// subpathsAtPath:不遞歸
NSArray *subpathArray = [fileManager contentsOfDirectoryAtPath:cachePath error:nil];
// 如果數組為空,說明沒有緩存或者用戶已經清理過,此時直接return
if (subpathArray.count == 0) {
#ifdef DEBUG
NSLog(@"此緩存路徑很干凈,不需要再清理了");
#else
#endif
return NO;
}
NSError *error = nil;
NSString *filePath = nil;
BOOL flag = NO;
for (NSString *subpath in subpathArray) {
filePath = [cachePath stringByAppendingPathComponent:subpath];
if ([fileManager fileExistsAtPath:cachePath]) {
// 刪除子文件夾
BOOL isRemoveSuccessed = [fileManager removeItemAtPath:filePath error:&error];
if (isRemoveSuccessed) { // 刪除成功
flag = YES;
}
}
}
if (NO == flag) {
#ifdef DEBUG
NSLog(@"提示:您已經清理了所有可以訪問的文件,不可訪問的文件無法刪除"); // 調試階段才打印
#else
#endif
}
return flag;
}
@end
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。