NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
[self folderSizeAtPath:cachesDir];
UILabel*cacheLab = [[UILabelalloc]initWithFrame:CGRectMake(0,10,60,20)];
cacheLab.textColor = [UIColorcolorWithHexString:@"#404040"];
cacheLab.numberOfLines=0;
cacheLab.textAlignment=NSTextAlignmentRight;
cacheLab.font = [UIFontsystemFontOfSize:14];
cacheLab.text=[NSStringstringWithFormat:@"%.2fM",[selffolderSizeAtPath:cachesDir]];
[self addSubview:cacheLab];
UITapGestureRecognizer* cache = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(cacheTap)];
[cacheLabaddGestureRecognizer:cache];
- (float ) folderSizeAtPath:(NSString*) folderPath{
NSFileManager* manager = [NSFileManagerdefaultManager];
if (![managerfileExistsAtPath:folderPath])return0;
NSEnumerator *childFilesEnumerator = [[managersubpathsAtPath:folderPath]objectEnumerator];//从前向后枚举器//////
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumeratornextObject]) !=nil){
//NSLog(@"fileName ==== %@",fileName);
NSString* fileAbsolutePath = [folderPathstringByAppendingPathComponent:fileName];
//NSLog(@"fileAbsolutePath ==== %@",fileAbsolutePath);
folderSize += [selffileSizeAtPath:fileAbsolutePath];
}
//NSLog(@"folderSize ==== %lld",folderSize);
return folderSize/(1024.0*1024.0);
}
//计算缓存文件的大小的M
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManagerdefaultManager];
if ([managerfileExistsAtPath:filePath]){
return [[managerattributesOfItemAtPath:filePatherror:nil]fileSize];
}
return0;
}
-(void)cacheTap{
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"温馨提示"
message:@"是否确定清除缓存?"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定",nil];
alert.delegate=self;
[alert show];
}
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex==0) {
}elseif (buttonIndex==1){
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesDir = [pathsobjectAtIndex:0];
NSArray *files = [[NSFileManagerdefaultManager]subpathsAtPath:cachesDir];
for (NSString *pin files) {
NSError *error;
NSString *path = [cachesDirstringByAppendingPathComponent:p];
if ([[NSFileManagerdefaultManager]fileExistsAtPath:path]) {
[[NSFileManagerdefaultManager]removeItemAtPath:patherror:&error];
}
}
[selfperformSelectorOnMainThread:@selector(clearCacheSuccess)withObject:nilwaitUntilDone:YES];
}
}
-(void)clearCacheSuccess
{
cacheLab.text=@"0M";
[HUDProgressshowInView:self.navigationController.viewwithTitle:@"清理缓存成功"type:HUDProgressTypeError];
}