Observe progress of Data download in Swift?

杀马特。学长 韩版系。学妹 提交于 2019-12-04 04:20:20

问题


I need to cache data that I receive from an remote url to a local URL. I am able to do this successfully with:

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

But I was wondering if there is some type of observer I can use to display a progress view as the data is written?


回答1:


Don't use Data(contentsOf: url) to make synchronous request for urls that are not local resources. You should use URLSession.To observe the progress you need to set urlsessiondownloaddelegate https://developer.apple.com/documentation/foundation/urlsessiondownloaddelegate and to monitor the progress, use the method

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

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



来源:https://stackoverflow.com/questions/46962037/observe-progress-of-data-download-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!