//
//LYClearCache.h
//清除缓存
//
//Created by李瑜on 16/8/1.
//Copyright © 2016年李瑜. All rights reserved.
//
#import
#import
@interfaceLYClearCache : NSObject
/**计算缓存大小
*
*参数:缓存文件夹路径
*
*
*/
+ (void)getCacheSizeWithPath:(NSString *)directoryPath Completion:(void(^)(NSString* sizeString))completion;
/**删除文件夹下的文件
*
*参数:缓存文件夹路径
*
*
*/
+ (void)removeDirectoryPath:(NSString *)directoryPath Completion:(void(^)(BOOLret))completion;
@end
//
//LYClearCache.m
//清除缓存
//
//Created by李瑜on 16/8/1.
//Copyright © 2016年李瑜. All rights reserved.
//
#import"LYClearCache.h"
@implementationLYClearCache
//获取文件夹内容大小
+ (void)getCacheSizeWithPath:(NSString *)directoryPath Completion:(void(^)(NSString* sizeString))completion
{
dispatch_async(dispatch_get_global_queue(0,0), ^{
//获取文件管理者
NSFileManager * manager = [NSFileManager defaultManager];
//获取文件夹下所有的子路径
NSArray * subPaths = [manager subpathsAtPath:directoryPath];
NSInteger totalSize =0;
for(NSString * subPathinsubPaths) {
NSString * filePath= [directoryPath stringByAppendingPathComponent:subPath];
if([filePath containsString:@".DS"]) {
continue;
}
//判断是否文件夹
BOOLisDirectory;
//判断文件夹是否存在
BOOLisExit = [manager fileExistsAtPath:filePath isDirectory:&isDirectory];
if(!isExit || isDirectory) {
continue;
}
NSDictionary * attr = [manager attributesOfItemAtPath:filePath error:nil];
NSInteger fileSize = [attr fileSize];
totalSize += fileSize;
}
NSString * sizeStr =@"";
if(totalSize >1000*1000) {
//MB
CGFloat sizeF = totalSize /1000.0/1000.0;
sizeStr = [NSString stringWithFormat:@"%.1fMB",sizeF];
}else{
sizeStr = [NSString stringWithFormat:@"缓存区很干净,无须清理"];
//KB
}
if(completion) {
completion(sizeStr);
}
});
}
//删除文件夹下的文件
+ (void)removeDirectoryPath:(NSString *)directoryPath Completion:(void(^)(BOOLret))completion
{
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSFileManager * manager = [NSFileManager defaultManager];
//获取文件夹下所有的子路径
NSArray * subPaths = [manager contentsOfDirectoryAtPath:directoryPath error:nil];
for(NSString * subPathinsubPaths) {
//拼接文件路径
NSString * filePath = [directoryPath stringByAppendingPathComponent:subPath];
//删除文件
[manager removeItemAtPath:filePath error:nil];
}
//完成回调
if(completion){
completion(YES);
}
});
}
@end