接著上篇下載word/pdf/txt等文檔的文章,此篇涉及到清除這些文檔。本文實現文件/文件夾大小的計算以及清除文件,還有清除SDWebImage緩存圖片的一些內容。不廢話,直接上代碼。
一.計算文件/文件夾大小
/**
獲取文件/文件夾大小
@param fileName 文件/文件夾路徑
@return 大小
*/
- (CGFloat)getFileSizeWithFileName:(NSString *)fileName {
//文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
//判斷字符串是否為文件/文件夾
BOOL dir = NO;
BOOL exists = [mgr fileExistsAtPath:fileName isDirectory:&dir];
//文件/文件夾不存在
if (exists == NO) return 0;
//self是文件夾
if (dir){
//遍歷文件夾中的所有內容
NSArray *subpaths = [mgr subpathsAtPath:fileName];
//計算文件夾大小
NSInteger totalByteSize = 0;
for (NSString *subpath in subpaths){
//拼接全路徑
NSString *fullSubPath = [fileName stringByAppendingPathComponent:subpath];
//判斷是否為文件
BOOL dir = NO;
[mgr fileExistsAtPath:fullSubPath isDirectory:&dir];
if (dir == NO){//是文件
NSDictionary *attr = [mgr attributesOfItemAtPath:fullSubPath error:nil];
totalByteSize += [attr[NSFileSize] integerValue];
}
}
return totalByteSize;
} else{//是文件
NSDictionary *attr = [mgr attributesOfItemAtPath:fileName error:nil];
return [attr[NSFileSize] floatValue];
}
}
二.獲取文件夾下文件大小和SDWebImage緩存大小
CGFloat totalSize = 0;
//獲取Documents下文件的總共大小
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
CGFloat docSize = [self getFileSizeWithFileName:documentsDirectory];
NKLog(@"docSize=%ld",(long)docSize);
//獲取SDWebimage緩存的圖片大小
CGFloat imageSize = [[SDImageCache sharedImageCache] getSize];
NKLog(@"imageSize=%lu",(unsigned long)imageSize);
//緩存圖片大小+下載的word文檔大小
totalSize = (docSize + imageSize)/1000/1000;
self.memeryLabel.text = [NSString stringWithFormat:@"%.2fM",totalSize];
三.清除文件和緩存圖片
/**
清除緩存
*/
-(void)clearMemery {
NSUInteger cacheSize = [[SDImageCache sharedImageCache] getSize];
if (cacheSize == 0) {
[MBProgressHUD showSuccess:@"沒有緩存" toView:self.view];
}else {
[[SDImageCache sharedImageCache] clearMemory];
[MBProgressHUD showMessage:@"正在清除緩存" toView:self.view];
//清除Documents下的word文檔
NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:DocumentsPath];
for (NSString *fileName in enumerator) {
[[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:fileName] error:nil];
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUD];
[MBProgressHUD showSuccess:@"清除緩存成功"];
[MBProgressHUD hideHUDForView:self.view];
self.memeryLabel.text = @"0.0M";
});
}
}
好了,實現了,慕言的世界!!!