口袋优选

YBCacheTool.m 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // YBCacheTool.m
  3. // ZCWL
  4. //
  5. // Created by ios-dev on 16/3/22.
  6. // Copyright © 2016年 com.zcwljs.cnge.app. All rights reserved.
  7. //
  8. #import "YBCacheTool.h"
  9. #import "YBMD5.h"
  10. #import "YBCacheConstant.h"
  11. @implementation YBCacheTool
  12. + (void)cacheForData:(NSData *)data fileName:(NSString *)fileName
  13. {
  14. NSString *path = [kCachePath stringByAppendingPathComponent:[YBMD5 md5:fileName]];
  15. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  16. [data writeToFile:path atomically:YES];
  17. });
  18. }
  19. + (NSData *)getCacheFileName:(NSString *)fileName
  20. {
  21. NSString *path = [kCachePath stringByAppendingPathComponent:[YBMD5 md5:fileName]];
  22. return [[NSData alloc] initWithContentsOfFile:path];
  23. }
  24. + (NSUInteger)getAFNSize
  25. {
  26. NSUInteger size = 0;
  27. NSFileManager *fm = [NSFileManager defaultManager];
  28. NSDirectoryEnumerator *fileEnumerator = [fm enumeratorAtPath:kCachePath];
  29. for (NSString *fileName in fileEnumerator) {
  30. NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];
  31. NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  32. size += [attrs fileSize];
  33. }
  34. return size;
  35. }
  36. + (NSUInteger)getSize
  37. {
  38. //获取AFN的缓存大小
  39. NSUInteger afnSize = [self getAFNSize];
  40. return afnSize;
  41. }
  42. + (void)clearAFNCache
  43. {
  44. NSFileManager *fm = [NSFileManager defaultManager];
  45. NSDirectoryEnumerator *fileEnumerator = [fm enumeratorAtPath:kCachePath];
  46. for (NSString *fileName in fileEnumerator) {
  47. NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];
  48. [fm removeItemAtPath:filePath error:nil];
  49. }
  50. }
  51. + (void)clearCache
  52. {
  53. [self clearAFNCache];
  54. }
  55. + (BOOL)isExpire:(NSString *)fileName
  56. {
  57. NSString *path = [kCachePath stringByAppendingPathComponent:[YBMD5 md5:fileName]];
  58. NSFileManager *fm = [NSFileManager defaultManager];
  59. NSDictionary *attributesDict = [fm attributesOfItemAtPath:path error:nil];
  60. NSDate *fileModificationDate = attributesDict[NSFileModificationDate];
  61. NSTimeInterval fileModificationTimestamp = [fileModificationDate timeIntervalSince1970];
  62. //现在的时间戳
  63. NSTimeInterval nowTimestamp = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
  64. return ((nowTimestamp-fileModificationTimestamp)>kYBCache_Expire_Time);
  65. }
  66. @end