DownloadHelper.m 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // DownloadHelper.m
  3. // BuguLive
  4. //
  5. // Created by voidcat on 2024/5/22.
  6. // Copyright © 2024 xfg. All rights reserved.
  7. //
  8. #import "DownloadHelper.h"
  9. @implementation DownloadHelper
  10. static DownloadHelper *sharedInstance;
  11. + (DownloadHelper *)sharedInstance {
  12. static dispatch_once_t onceToken;
  13. dispatch_once(&onceToken, ^{
  14. sharedInstance = [[DownloadHelper alloc] init];
  15. });
  16. return sharedInstance;
  17. }
  18. - (void)downloadOrFetchFromCache:(NSString *)urlString completion:(void(^)(NSString *filePath))completion {
  19. [[BGHUDHelper sharedInstance] syncLoading];
  20. NSString *key = [urlString md5];
  21. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  22. NSString *cachedPath = [defaults objectForKey:key];
  23. if (cachedPath) {
  24. [[BGHUDHelper sharedInstance] syncStopLoading];
  25. completion(cachedPath);
  26. } else {
  27. NSURL *url = [NSURL URLWithString:urlString];
  28. NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession]
  29. downloadTaskWithURL:url
  30. completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  31. NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  32. NSString *destinationPath = [documentsPath stringByAppendingPathComponent:response.suggestedFilename];
  33. NSError *fileError;
  34. [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&fileError];
  35. if (!fileError) {
  36. [defaults setObject:destinationPath forKey:key];
  37. [[BGHUDHelper sharedInstance] syncStopLoading];
  38. completion(destinationPath);
  39. }
  40. }
  41. ];
  42. [downloadTask resume];
  43. }
  44. }
  45. @end