//
//LYClearCache.h
//清除緩存
//
//Created by李瑜on 16/8/1.
//Copyright ? 2016年李瑜. All rights reserved.
//
#import
#import
@interfaceLYClearCache : NSObject
/**計算緩存大小
*
*參數(shù):緩存文件夾路徑
*
*
*/
+ (void)getCacheSizeWithPath:(NSString *)directoryPath Completion:(void(^)(NSString* sizeString))completion;
/**刪除文件夾下的文件
*
*參數(shù):緩存文件夾路徑
*
*
*/
+ (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:@"緩存區(qū)很干凈灭美,無須清理"];
//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