清除app緩存

//

//LYClearCache.h

//清除緩存

//

//Created by李瑜on 16/8/1.

//Copyright ? 2016年李瑜. All rights reserved.

//

#import

#import

@interfaceLYClearCache : NSObject

/**計(jì)算緩存大小

*

*參數(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

//獲取文件夾內(nèi)容大小

+ (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];

}

//完成回調(diào)

if(completion){

completion(YES);

}

});

}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容