SZKCleanCache.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // SZKCleanCache.m
  3. // CleanCache
  4. //
  5. // Created by sunzhaokai on 16/5/11.
  6. // Copyright © 2016年 孙赵凯. All rights reserved.
  7. //
  8. #import "SZKCleanCache.h"
  9. @implementation SZKCleanCache
  10. /**
  11. * 清理缓存
  12. */
  13. +(void)cleanCache:(cleanCacheBlock)block
  14. {
  15. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  16. //文件路径
  17. NSString *directoryPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  18. NSArray *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
  19. for (NSString *subPath in subpaths) {
  20. NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
  21. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  22. }
  23. //返回主线程
  24. dispatch_async(dispatch_get_main_queue(), ^{
  25. block();
  26. });
  27. });
  28. }
  29. /**
  30. * 计算整个目录大小
  31. */
  32. +(float)folderSizeAtPath
  33. {
  34. NSString *folderPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  35. NSFileManager * manager=[NSFileManager defaultManager ];
  36. if (![manager fileExistsAtPath :folderPath]) {
  37. return 0 ;
  38. }
  39. NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
  40. NSString * fileName;
  41. long long folderSize = 0 ;
  42. while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
  43. NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
  44. folderSize += [ self fileSizeAtPath :fileAbsolutePath];
  45. }
  46. return folderSize/( 1024.0 * 1024.0 );
  47. }
  48. /**
  49. * 计算单个文件大小
  50. */
  51. +(long long)fileSizeAtPath:(NSString *)filePath{
  52. NSFileManager *manager = [NSFileManager defaultManager];
  53. if ([manager fileExistsAtPath :filePath]){
  54. return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize];
  55. }
  56. return 0 ;
  57. }
  58. @end