Setup for Assets downloading(資源下載設(shè)置)--Moya文檔

Setup for Assets downloading(資源下載設(shè)置)

這里我們?nèi)稳幌蚰阏故救绾蝸韺?shí)現(xiàn)一個簡單的資源下載設(shè)置。首先,我們創(chuàng)建一個新的TargetType協(xié)議的實(shí)現(xiàn)

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<Assets>()

  init() { }

  func load(asset: Asset, completion: ((Result<URL, MoyaError>) -> 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
        }
    }
}

總結(jié) 這小節(jié)的核心:

  1. 創(chuàng)建好一個資源下載器AssetLoader(它包裝了MoyaProvider對象)
  2. 創(chuàng)建好一個資源下載的TargetType。
  3. 如何使用AssetLoader
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容