iOS 清理本地缓存

来源:互联网 发布:Js定义字符串编码 编辑:程序博客网 时间:2024/05/17 03:28

下面就以沙盒里面的零时文件tmp为清理对象;

 -(void)func{ 

   CGFloat size = [selffolderSizeAtPath:NSTemporaryDirectory()];

    

    NSString *message = size > 1 ? [NSString stringWithFormat:@"缓存%.2fM, 删除缓存\n是否清除缓存?", size] : [NSStringstringWithFormat:@"缓存%.2fK, 删除缓存", size *1024.0];

    

    UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"提示"message:message preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction *sureAction = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {

        [selfcleanCaches:NSTemporaryDirectory()];

    }];

    

    UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction *action) {

        

    }];

    // Add the actions.

    [alertController addAction:cancelAction];

    [alertController addAction:sureAction];

    [selfpresentViewController:alertController animated:YEScompletion:nil];

}

#pragma mark- 计算缓存大小

// 计算目录大小

- (CGFloat)folderSizeAtPath:(NSString *)path{

    // 利用NSFileManager实现对文件的管理

    NSFileManager *manager = [NSFileManagerdefaultManager];

    CGFloat size = 0;

    if ([manager fileExistsAtPath:path]) {

        // 获取该目录下的文件,计算其大小

        NSArray *childrenFile = [manager subpathsAtPath:path];

        for (NSString *fileNamein childrenFile) {

            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];

            size += [manager attributesOfItemAtPath:absolutePatherror:nil].fileSize;

        }

        // 将大小转化为M

        return size / 1024.0 / 1024.0;

    }

    return 0;

}

// 根据路径删除文件

- (void)cleanCaches:(NSString *)path{

    // 利用NSFileManager实现对文件的管理

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    if ([fileManager fileExistsAtPath:path]) {

        // 获取该路径下面的文件名

        NSArray *childrenFiles = [fileManager subpathsAtPath:path];

        for (NSString *fileNamein childrenFiles) {

            // 拼接路径

            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];

            // 将文件删除

            [fileManager removeItemAtPath:absolutePatherror:nil];

        }

    }

}


原创粉丝点击