iOS 清除缓存

时间:2021-08-16 09:10:26

iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒。它包含三个文件夹:

Documents: 苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录,如用户信息等永久性文件;

Library: 它包含两个文件夹 caches 和 preferences 
Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除,如图片、视频缓存; 
Library/Preferences:包含应用程序的偏好设置文件;

Temp:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。 
下面是获取沙盒路径的方法:

1、//沙盒的根目录 NSString *homePath = NSHomeDirectory();

2、//沙盒Documents路径 NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

3、//沙盒中Library路径 NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];

4、//沙盒中Library/Caches路径 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

5、//沙盒中Temp路径 NSString *tempPath = NSTemporaryDirectory();

//计算文件夹的大小

-(float)calculateFolderSizeWithPath:(NSString *)path{

NSFileManager *fileManager=[NSFileManager defaultManager];

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

cachePath=[cachePath stringByAppendingPathComponent:path];

CGFloat folderSize=0;

if ([fileManager fileExistsAtPath:cachePath])

{

NSArray *childFiles=[fileManager subpathsAtPath:cachePath];

for (NSString *fileName in childFiles)

{

NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];

CGFloat size=[self calculateFileSizeWithPath:fileAbsolutePath];

folderSize += size;

NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);

}

//SDWebImage框架自身计算缓存

folderSize+=[[SDImageCache sharedImageCache] getSize];

return folderSize/1024.0/1024.0;

}

return 0;

}

//计算单个文件大小

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

NSFileManager *fileManager=[NSFileManager defaultManager];

if([fileManager fileExistsAtPath:path]){

CGFloat size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;

return size;

}

return 0;

}

- (void)clearCacheClick

{

NSArray *arr_Path = @[@"/Media",@"/Music",@"/Voice"];

[[UIView alloc]showHUDWithTitle:@"正在清除缓存···" WithState:1];

//一是清除SDWebImage的缓存,二是清除自定义文件缓存

[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{

dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

for (NSString *pathName in arr_Path) {

NSString *fileAbsolutePath = [documentDir stringByAppendingPathComponent:pathName];

NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:fileAbsolutePath]) {

[fileManager removeItemAtPath:fileAbsolutePath error:nil];

[fileManager createDirectoryAtPath:fileAbsolutePath withIntermediateDirectories:YES attributes:nil error:nil];

}

}

dispatch_async(dispatch_get_main_queue(), ^{

[[UIView alloc]showAndHideHUDWithTitle:@"清除完成" WithState:0];

// 设置文字

self.lable_Cache.text = @"0.00 MB";

});

});

}];

}