美文网首页
APP清空缓存

APP清空缓存

作者: CY水漆 | 来源:发表于2024-03-14 10:40 被阅读0次

#import  <SDImageCache.h>

-(NSString *)getFileCache{

    self.cacheStr = [NSString stringWithFormat:@"%.2fM",[self filePath]];

    return self.cacheStr;

}

- (float)filePath {

    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];

    return[selffolderSizeAtPath:cachPath];

}

//遍历文件夹获得文件夹大小,返回多少M

- (float)folderSizeAtPath:(NSString*) folderPath {

    NSFileManager* manager = [NSFileManager defaultManager];

    if(![managerfileExistsAtPath:folderPath])return0;

    NSEnumerator*childFilesEnumerator = [[managersubpathsAtPath:folderPath]objectEnumerator];

    NSString* fileName;

    longlongfolderSize =0;

    while((fileName = [childFilesEnumeratornextObject]) !=nil){

        NSString* fileAbsolutePath = [folderPath    stringByAppendingPathComponent:fileName];

        folderSize += [selffileSizeAtPath:fileAbsolutePath];

    }

    //SDWebImage框架自身计算缓存的实现

    folderSize += [[SDImageCache sharedImageCache] totalDiskSize];

    returnfolderSize/(1024.0*1024.0);

}

- (longlong)fileSizeAtPath:(NSString*) filePath{

    NSFileManager* manager = [NSFileManager defaultManager];

    if([managerfileExistsAtPath:filePath]){

        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

    }

    return0;

}

- (void)clearCacheDidSelected {

    MJWeakSelf

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%@,确定要清理缓存吗?",self.cacheStr]  preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [weakSelf.tableViewreloadData];

        [weakSelfclearCache];

    }];

    [alertControlleraddAction:cancelAction];

    [alertControlleraddAction:confirmAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)clearCache {

    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];

    NSFileManager *fileManager=[NSFileManager defaultManager];

    if([fileManagerfileExistsAtPath:cachPath]) {

        NSArray*childerFiles=[fileManagersubpathsAtPath:cachPath];

        for(NSString*fileNameinchilderFiles) {

            //如有需要,加入条件,过滤掉不想删除的文件

            NSString*absolutePath=[cachPathstringByAppendingPathComponent:fileName];

            [fileManagerremoveItemAtPath:absolutePatherror:nil];

        }

    }

    [[SDImageCache sharedImageCache] clearMemory];

}

相关文章

网友评论

      本文标题:APP清空缓存

      本文链接:https://www.haomeiwen.com/subject/zilltrtx.html