1. 计算缓存路径下的文件大小
#pragma mark 计算 path路径 下的缓存大小
- (float)checkTmpSizeWithFilePath:(NSString *)path
{
float totalSize = 0;
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
for (NSString *fileName in fileEnumerator)
{
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
unsigned long long length = [attrs fileSize];
totalSize += length / 1024.0 / 1024.0;
}
// NSLog(@"tmp size is %.2f",totalSize);
return totalSize;
}
2.清除缓存文件夹下的文件
#pragma mark 清除 path路径下的缓存
- (void)clearCacheWithFilePath:(NSString *)path {
// [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
// 文件管理
NSFileManager *flieManager = [NSFileManager defaultManager];
// NSDirectoryEnumerator 枚举了某个目录的内容,返回所有文件和目录的路径名中包含该目录。这些路径名是相对于目录
NSDirectoryEnumerator *fileEnumerator = [flieManager enumeratorAtPath:path];
for (NSString *fileName in fileEnumerator)
{
// 文件路径
NSString *filePath = [path stringByAppendingPathComponent:fileName];
// 删除文件
[flieManager removeItemAtPath:filePath error:nil];
NSLog(@"filePath is --%@",filePath);
}
}
3.清除触发事件
{
// 缓存路径(根据自己APP的缓存路径更改)
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
CGFloat fileSize = [self checkTmpSizeWithFilePath:filePath];
NSString *mesge = 1 <= fileSize ? [NSString stringWithFormat:@"清理缓存(%.2fM)",fileSize] : [NSString stringWithFormat:@"清理缓存(%.2fK)",fileSize * 1024];
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"清除缓存" message:mesge preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"清除" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self clearCacheWithFilePath:filePath];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
}];
[alertC addAction:sureAction];
[alertC addAction:cancelAction];
[self.navigationController presentViewController:alertC animated:YES completion:nil];
}
网友评论