在 Swift 观察数据下载进度?

Observe progress of Data download in Swift?

我需要将从远程 url 接收到的数据缓存到本地 URL。我能够通过以下方式成功完成此操作:

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

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

不要使用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