#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIAlertView *alertView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 100);
[button setTitle:@"清理緩存" forState:UIControlStateNormal];
[button setTitleColor:[UIColor cyanColor] forState:UIControlStateNormal];
button.layer.cornerRadius = 5;
button.layer.masksToBounds = YES;
[button addTarget:self action:@selector(clearCache) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
#pragma mark -檢查緩存
- (void)clearCache{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fileManager=[NSFileManager defaultManager];
float folderSize;
if ([fileManager fileExistsAtPath:path]) {
//拿到算有檔案的數組
NSArray *childerFiles = [fileManager subpathsAtPath:path];
//拿到每個檔案的名字,如有有不想清除的檔案就在這裡判斷
for (NSString *fileName in childerFiles) {
//将路徑拼接到一起
NSString *fullPath = [path stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fullPath];
}
self.alertView = [[UIAlertView alloc] initWithTitle:@"清理緩存" message:[NSString stringWithFormat:@"緩存大小為%.2fM,确定要清理緩存嗎?", folderSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[self.alertView show];
self.alertView.delegate = self;
}
}
//計算單個檔案夾的大小
-(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;
}
#pragma mark -彈框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex) {
//點選了确定,周遊整個caches檔案,将裡面的緩存清空
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
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];
}
}
}
self.alertView = nil;
}