QNDnsCacheFile.m 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 **)error{
  15. NSError *err = nil;
  16. [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&err];
  17. if (err != nil) {
  18. if (error != nil) *error = err;
  19. return nil;
  20. }
  21. QNDnsCacheFile *f = [[QNDnsCacheFile alloc] init];
  22. f.directory = directory;
  23. return f;
  24. }
  25. - (NSError *)set:(NSString *)key data:(NSData *)value {
  26. @synchronized (self) {
  27. NSError *error;
  28. NSFileManager *fileManager = [NSFileManager defaultManager];
  29. NSString *filePath = [self pathOfKey:key];
  30. if ([fileManager fileExistsAtPath:filePath]) {
  31. [fileManager removeItemAtPath:filePath error:&error];
  32. }
  33. [fileManager createFileAtPath:filePath contents:value attributes:nil];
  34. return error;
  35. }
  36. }
  37. - (NSData *)get:(NSString *)key {
  38. return [NSData dataWithContentsOfFile:[self pathOfKey:key]];
  39. }
  40. - (NSError *)del:(NSString *)key {
  41. @synchronized (self) {
  42. NSError *error = nil;
  43. NSString *path = [self pathOfKey:key];
  44. if (path) {
  45. NSFileManager *fileManager = [NSFileManager defaultManager];
  46. [fileManager removeItemAtPath:path error:&error];
  47. }
  48. return error;
  49. }
  50. }
  51. - (void)clearCache:(NSError *__autoreleasing _Nullable *)error {
  52. @synchronized (self) {
  53. NSError *err;
  54. NSFileManager *fileManager = [NSFileManager defaultManager];
  55. [fileManager removeItemAtPath:self.directory error:&err];
  56. if (err != nil) {
  57. if (error != nil) *error = err;
  58. return;
  59. }
  60. [fileManager createDirectoryAtPath:self.directory withIntermediateDirectories:YES attributes:nil error:&err];
  61. if (error != nil) {
  62. *error = err;
  63. }
  64. }
  65. }
  66. - (NSString *)getFileName{
  67. return @"dnsCache";
  68. }
  69. - (NSString *)pathOfKey:(NSString *)key {
  70. return [QNDnsCacheFile pathJoin:key path:_directory];
  71. }
  72. + (NSString *)pathJoin:(NSString *)key
  73. path:(NSString *)path {
  74. return [[NSString alloc] initWithFormat:@"%@/%@", path, key];
  75. }
  76. @end