清除缓存的功能
清除缓存在每一个应用是一个很常见的功能,今天这里小结一下。
将数据永久性的存储我们称为数据持久化,其本质是将数据存储到文件中,放到本地,共手机使用。
由于缓存文件是存在APP沙盒文件中的,所以我们要实现缓存的清除,需要通过NSFileManager的API来对缓存的清除,
沙盒机制
沙盒是针对安装到移动终端上的每一个APP单独生成的文件夹,存储用户的个性设置,每一个用户的内容不同,只具有读写功能。
沙盒文件夹的几个路径文件夹
Documents文件夹
存放数据持久化文件,比如:通讯录信息,备份时也备份该文件夹内容,该文件夹内容不能过大,否则无法上传到AppStore
获取方法
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"doo = %@",documentsPath);
Library文件夹
Library 包含了Documents,Preferences,tmp。
Caches:存放缓存文件,下载的视频,图片,音频,小说都在该文件夹下
Preferences:存放用户偏好设置,比如:存储用户的用户名和密码
tmp:存放临时文件,比如:下载的zip包,解压之后将zip包删除,将解压内容移到Caches文件夹下.
Caches获取方法
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"cachesPath = %@",cachesPath);
下面的代码是可以封装成一个 tool类
/**
* 获取缓存路径
*
* @return 缓存路径
*/
+(NSString *)cachePath;
/**
* 清除缓存
*/
+(BOOL)clearCache;
/**
* 获取缓存大小(单位:M)
*
* @return 缓存大小
*/
+ (float)cacheSize;
/**
* 获取缓存大小,(以..kb/..M)形式获取
* 小于1M,以kb形式返回,大于1M,以M形式返回
* @return 缓存大小+单位
*/
+(NSString *)cacheSizeFormat;
/**
* 获取缓存路径
*
* @return 缓存路径
*/
+(NSString *)cachePath {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
return cachesPath;
}
/**
* 清除缓存
*/
+(BOOL)clearCache {
///创建文件管理类
NSFileManager *fileManager = [NSFileManager defaultManager];
///获取路径
NSString *path = [self cachePath];
BOOL result = [fileManager removeItemAtPath:path error:nil];
[self checkDirectory:path];
return result;
}
//检查路径
+(void)checkDirectory:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {
[self createBaseDirectoryAtPath:path];
} else {
if (!isDir) {
NSError *error = nil;
[fileManager removeItemAtPath:path error:&error];
[self createBaseDirectoryAtPath:path];
}
}
}
+ (void)createBaseDirectoryAtPath:(NSString *)path {
__autoreleasing NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES
attributes:nil error:&error];
if (error) {
DebugLog(@"create cache directory failed, error = %@", error);
} else {
DebugLog(@"path = %@",path);
[self addDoNotBackupAttribute:path];
}
}
+ (void)addDoNotBackupAttribute:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
[url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
if (error) {
DebugLog(@"error to set do not backup attribute, error = %@", error);
}
}
/**
* 获取缓存大小(单位:M)
*
* @return 缓存大小
*/
+ (float)cacheSize {
NSString *directoryPath = [self cachePath];
BOOL isDir = NO;
unsigned long long total = 0;
if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir]) {
if (isDir) {
NSError *error = nil;
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:&error];
if (error == nil) {
for (NSString *subpath in array) {
NSString *path = [directoryPath stringByAppendingPathComponent:subpath];
NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path
error:&error];
if (!error) {
total += [dict[NSFileSize] unsignedIntegerValue];
}
}
}
}
}
return total/(1024.0*1024.0);
}
/**
* 获取缓存大小,(以..kb/..M)形式获取
* 小于1M,以kb形式返回,大于1M,以M形式返回
* @return 缓存大小+单位
*/
+(NSString *)cacheSizeFormat {
NSString *sizeUnitString;
float size = [self cacheSize];
if(size < 1)
{
size *= 1024.0;//小于1M转化为kb
sizeUnitString = [NSString stringWithFormat:@"%.1fkb",size];
}
else{
sizeUnitString = [NSString stringWithFormat:@"%.1fM",size];
}
return sizeUnitString;
}
当然我们在APP 中有时也会加载webView,那个有时webView的缓存也要清除,我们主要清除是Cookie
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
_webView = nil;
[self cleanCacheAndCookie];
}
/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
//清除cookies
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}
//清除UIWebView的缓存
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
}