清空缓存功能一般在一个项目中都会用到,一般的缓存会保存在Library的Canche目录下(当然,如果是自己写在了别的目录下,就需要另外清空了)
首先获取Library下的Canche缓存的大小,这儿主要是照顾需要显示缓存大小的项目
代码如下:
- (void)GetCanchesSizeWithCompletionBlock:(void(^)(NSInteger totoalsize))completion {
NSURL *diskCacheURL = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] isDirectory:YES];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSUInteger totalSize = 0;
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:@[NSFileSize]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
for (NSURL *fileURL in fileEnumerator) {
NSNumber *fileSize;
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
totalSize += [fileSize unsignedIntegerValue];
}
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(totalSize);
});
}
});
}
然后清空缓存
代码如下:
- (void)clearCanchesCompletion:(void(^)(void))completion
{
NSString *diskCacheURL = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSArray *canchefiles = [[NSFileManager defaultManager] subpathsAtPath:diskCacheURL];
for (NSString *subfile in canchefiles) {// 遍历目录
NSError *error;
NSString *path = [diskCacheURL stringByAppendingPathComponent:subfile];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
}
}
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
}
这样就可以清空Canche目录的缓存文件了