【问题标题】:Observe progress of Data download in Swift?观察 Swift 中数据下载的进度?
【发布时间】:2018-04-08 06:59:57
【问题描述】:

我需要将从远程 URL 接收到的数据缓存到本地 URL。我能够成功地做到这一点:

let dataToCache = try Data(contentsOf: url) try dataToCache.write(to: cacheURL)

但我想知道是否有某种类型的观察者可以用来在数据写入时显示进度视图?

【问题讨论】:

    标签: swift download progress observers


    【解决方案1】:

    不要使用Data(contentsOf: url)对非本地资源的url进行同步请求。您应该使用URLSession。要观察进度,您需要设置urlsessiondownloaddelegate https://developer.apple.com/documentation/foundation/urlsessiondownloaddelegate 并监控进度,使用方法

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    

    https://developer.apple.com/documentation/foundation/urlsessiondownloaddelegate/1409408-urlsession

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 2016-12-03
      相关资源
      最近更新 更多