//计算缓存值得大小
float tmpSize = 0;
NSString *diskCachePath= [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSDirectoryEnumerator *fileEnumrator = [[NSFileManager defaultManager] enumeratorAtPath:diskCachePath];
for (NSString *fileName in fileEnumrator) {
NSString *filePath = [diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
unsigned long long length = [attrs fileSize];
tmpSize += length/1024.0/1024.0;
}
NSLog(@"tmp size is %.2f",tmpSize);
self.tempLabel.text = [NSString stringWithFormat:@"%.2fM",tmpSize];
//执行清除缓存操作.放在子线程中进行.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
NSLog(@"files:%ld",(unsigned long)[files count]);
for (NSString *p in files) {
NSError *error;
NSString *path = [cachPath stringByAppendingPathComponent:p];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
}
}
[self performSelectorOnMainThread:@selector(clearCachesSuccess) withObject:nil waitUntilDone:YES];
});
//清楚缓存
- (void)clearCachesSuccess{
[self myAlertMessage:@"是否清除缓存"];
}
#pragma mark------提示框
- (void)myAlertMessage:(NSString*)message{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message: message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
// 开始清空
self.tempLabel.text = @"";
NSLog(@"清除成功");
}];
UIAlertAction *cancelACtion = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:nil];
[alertController addAction:sureAction];
[alertController addAction:cancelACtion];
[self presentViewController:alertController animated:YES completion:nil];
}