swift-download-manager

一个使用纯 swift 代码的下载管理器。

存储到设备的文件系统,并跟踪正在进行、已完成和已中断的下载。

该代码为下载提供了一个通用结构,当前版本实现了

ImageDownloaderInteractor 的示例用法

import swift_download_manager
// ...
override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   ImageDownloaderInteractor().getOrDownloadImage(remoteUrl: url) { result in
         switch result {
            case let .success(image):
            // use image
            case let .failure(error):
            // handle error
         }
    }
}

对于这种情况,ImageDownloaderInteractor 将尝试启动或恢复图像的已中断下载,基于给定的 URL。

DefaultDownloadInteractor 的示例用法

import swift_download_manager
// ...
final class YourCustomDownloadInteractor {
  private let defaultDownloadInteractor = DefaultDownloadInteractor() // you should use protocols 😄 and dependency injection for testing
  // `YourSomething` can be anything you like an UIImage, a PDF whatever you need to download, etc
  // you would just need to use the local url provided in the completion of DefaultDownloadManager to cast/load 
  func getOrDownloadSomething(remoteUrl url: URL, completion: @escaping (Result<YourSomething>, DownloadError)) {
     defaultDownloadManager.getOrDownload(remoteUrl: url) { result in 
     // here for example URL is used to create a Data object and based on that get an UIImage
        completion(
          result.map { url in
             (try? Data(contentsOf: url)).map { UIImage(data: $0)}
          }
        )
     }
  }
}