iOS拓展-手动清除缓存

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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,981评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,467评论 25 708
  • 回到燕国后,苏秦一直在默默等待机会,这一等就是七八年的时间,这期间齐国发生了一件大事,齐闵王与孟尝君因彼此政见不和...
    大任于斯阅读 684评论 0 2
  • 《暗时间》这本书的难度的确要比前两本大一点,今天听了语音主要的感想有以下两个方面: 1,写作对大脑有益。首先,大脑...
    桃花小境容阅读 359评论 0 0
  • NSURLProtectionSpace : 需要认证的服务器或域, 是所有进来的 NSURLAuthentica...
    spbreak阅读 266评论 0 0