Setup for Assets downloading(资源下载设置)--Moya文档

Setup for Assets downloading(资源下载设置)

这里我们任然向你展示如何来实现一个简单的资源下载设置。首先,我们创建一个新的TargetType协议的实现

fileprivate static let assetDir: URL = {
  let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  return directoryURLs.first ?? NSTemporaryDirectory()
}()


enum Asset: TargetType {
  case star
  case checkmark

  var baseURL: URL { /* ... */ }

  var assetName: String {
    switch self {
    case .star: return "star.png"
    case .checkmark: return "checkmark.png"
    }
  }

  var path: String {
    return "/assets/" + assetName
  }

  var localLocation: URL {
    return assetDir.appendingPathComponent(assetName)
  }

  var downloadDestination: DownloadDestination {
    return { _, _ in return (self.localLocation, .removePreviousFile) }
  }

  var task: Task {
    return .download(downloadDestination)
  }

  /*
    Rest of TargetType
  */
}

然后使用AssetLoader来包装MoyaProvider

final class AssetLoader {
  let provider = MoyaProvider()

  init() { }

  func load(asset: Asset, completion: ((Result) -> Void)? = nil) {
    if FileManager.default.fileExists(atPath: asset.localLocation.path) {
      completion?(.success(asset.localLocation))
      return
    }

    provider.request(asset) { result in 
      switch result {
      case .success:
        completion?(.success(asset.localLocation))
      case let .failure(error):
        return completion?(.failure(error))
      }
    }
  }
}

这就完毕了.然后使用AssetLoader

final class TestViewModel {
    let loader: AssetLoader

    init(loader: AssetLoader = AssetLoader()) {
        self.loader = loader
    }

    func loadImage() {
        loader.load(asset: .star) { result in
            // handle the result
        }
    }
}

总结 这小节的核心:

  1. 创建好一个资源下载器AssetLoader(它包装了MoyaProvider对象)
  2. 创建好一个资源下载的TargetType。
  3. 如何使用AssetLoader

你可能感兴趣的:(Setup for Assets downloading(资源下载设置)--Moya文档)