QNDnsCacheFile.m 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // QNDnsCacheFile.m
  3. // QnDNS
  4. //
  5. // Created by yangsen on 2020/3/26.
  6. // Copyright © 2020 com.qiniu. All rights reserved.
  7. //
  8. #import "QNDnsCacheFile.h"
  9. @interface QNDnsCacheFile()
  10. @property(nonatomic, copy)NSString *directory;
  11. @end
  12. @implementation QNDnsCacheFile
  13. + (instancetype)dnsCacheFile:(NSString *)directory
  14. error:(NSError **)perror{
  15. [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:perror];
  16. if (*perror != nil) {
  17. return nil;
  18. }
  19. QNDnsCacheFile *f = [[QNDnsCacheFile alloc] init];
  20. f.directory = directory;
  21. return f;
  22. }
  23. - (NSError *)set:(NSString *)key
  24. data:(NSData *)value {
  25. NSError *error;
  26. NSFileManager *fileManager = [NSFileManager defaultManager];
  27. NSString *filePath = [self pathOfKey:key];
  28. [fileManager createFileAtPath:filePath contents:value attributes:nil];
  29. return error;
  30. }
  31. - (NSData *)get:(NSString *)key {
  32. return [NSData dataWithContentsOfFile:[self pathOfKey:key]];
  33. }
  34. - (NSError *)del:(NSString *)key {
  35. NSError *error = nil;
  36. NSString *path = [self pathOfKey:key];
  37. if (path) {
  38. NSFileManager *fileManager = [NSFileManager defaultManager];
  39. [fileManager removeItemAtPath:path error:&error];
  40. }
  41. return error;
  42. }
  43. - (NSString *)getFileName{
  44. return @"dnsCache";
  45. }
  46. - (NSString *)pathOfKey:(NSString *)key {
  47. return [QNDnsCacheFile pathJoin:key path:_directory];
  48. }
  49. + (NSString *)pathJoin:(NSString *)key
  50. path:(NSString *)path {
  51. return [[NSString alloc] initWithFormat:@"%@/%@", path, key];
  52. }
  53. @end