iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒。它包含三个文件夹:
Documents: 苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录,如用户信息等永久性文件;
Library: 它包含两个文件夹 caches 和 preferences
Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除,如图片、视频缓存;
Library/Preferences:包含应用程序的偏好设置文件;
Temp:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。
下面是获取沙盒路径的方法:
//沙盒的根目录
NSString *homePath = NSHomeDirectory();
//沙盒Documents路径
NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//沙盒中Library路径
NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
//沙盒中Library/Caches路径
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//沙盒中Temp路径
NSString *tempPath = NSTemporaryDirectory();
APPStore中有一条明确规定,你的APP中缓存文件只能保存在沙盒路径下Caches文件夹或Temp文件夹下,不然将会被拒。而Temp文件夹下内容将会在APP退出时自动清除,所以我们清除APP缓存主要是清除Caches文件夹下的内容。
1、如果你只想清除图片缓存,且是用SDWebImage加载的网络图片,那么你可以用SDWebImage内部封装方法清除图片缓存
//导入头文件
#import <SDImageCache.h>
//获取缓存图片的大小(字节)
NSUInteger bytesCache = [[SDImageCache sharedImageCache] getSize];
//换算成 MB (注意iOS中的字节之间的换算是1000不是1024)
float MBCache = bytesCache/1000/1000;
//异步清除图片缓存 (磁盘中的)
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[[SDImageCache sharedImageCache] clearDisk];
});
2、如果你想清除所有的缓存文件(包括图片、视频、音频等), 那你可以用如下方法。需要你把caches的路径传过去,然后计算caches文件夹下内容的大小,然后根据其大小再判断是否清除缓存。
/**
* 根据传过来的路径计算文件夹里内容或文件的大小
*
* @param filePath 文件夹或文件的路径
*
* @return 大小
*/
- (NSUInteger)calculateFileSize:(NSString *)filePath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
//是否为文件
BOOL isFile = NO;
//判断文件或文件夹是否存在(也就是判断filePath是否是一个正确的路径)
BOOL isExist = [fileManager fileExistsAtPath:filePath isDirectory:&isFile];
if(!isExist) return 0;//不存在返回0
if(!isFile)//是文件
{
return [[fileManager attributesOfItemAtPath:filePath error:nil][NSFileSize] integerValue];
}
else //是文件夹
{
//遍历文件夹中的所有内容
NSArray *subPaths = [fileManager subpathsAtPath:filePath];
NSUInteger totalBytes = 0;
for(NSString *subPath in subPaths)
{
//NSLog(@"文件夹下的全部内容的路径:%@", subPath);
//获取全路径
NSString *fullPath = [filePath stringByAppendingString:[NSString stringWithFormat:@"/%@", subPath]];
BOOL dir= NO;
[fileManager fileExistsAtPath:fullPath isDirectory:&dir];
if(!dir)//是文件就计算大小,注意文件夹是没有大小的所以就不用计算了
{
totalBytes += [[fileManager attributesOfItemAtPath:fullPath error:nil][NSFileSize] integerValue];
}
}
return totalBytes;
}
}
清缓存很简单:
//根据路径删除文件或文件夹
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];