Observe progress of Data download in Swift?

2019-02-25 02:01发布

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条回答
等我变得足够好
2楼-- · 2019-02-25 02:18

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

查看更多
登录 后发表回答