1. 程式人生 > >iOS APP快取清理

iOS APP快取清理

- (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;
}