观察Swift中数据下载的进度? [英] Observe progress of Data download in Swift?

查看:52
本文介绍了观察Swift中数据下载的进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

这篇关于观察Swift中数据下载的进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆