简体   繁体   English

从 URLSession.shared.dataTask 获取当前进度

[英]Get Current Progress from URLSession.shared.dataTask

我需要获取 GET 请求的数据任务的当前进度(已接收和总字节数),以便从此数据制作进度加载指示器。

Add URLSessionDownloadDelegate , create a URLSession with delegate添加URLSessionDownloadDelegate ,使用委托创建一个URLSession

URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

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

    _progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
}

There are three types of session tasks.会话任务分为三种类型。 This is copied from Apple's websitelink .这是从 Apple 的网站链接复制的。

  1. Data tasks send and receive data using NSData objects.数据任务使用 NSData 对象发送和接收数据。 Data tasks are intended for short, often interactive requests to a server.数据任务用于对服务器进行简短的、通常是交互式的请求。
  2. Upload tasks are similar to data tasks, but they also send data (often in the form of a file), and support background uploads while the app isn't running.上传任务类似于数据任务,但它们也发送数据(通常以文件的形式),并支持在应用程序未运行时后台上传。
  3. Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app isn't running.下载任务以文件的形式检索数据,并在应用程序未运行时支持后台下载和上传。

You should use the download task instead of data task because its delegate methods will allow you to track the download progress.您应该使用下载任务而不是数据任务,因为它的委托方法将允许您跟踪下载进度。 Here is the link to the download delegate methods that call what you are asking for. 是调用您所要求的下载委托方法的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask 获取URL响应状态代码URLSession.shared.dataTask - Get http response status code of URLSession.shared.dataTask Swift URLSession.shared.dataTask GET Request -1001返回超时 - Swift URLSession.shared.dataTask GET Request -1001 returns timeout 在URLSession.shared.dataTask之后调用performSegue - Call performSegue after URLSession.shared.dataTask URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) 如何获取请求中标头的值(URLSession.shared.dataTask(with:request){(数据,响应,错误) - How get value of headers in request (URLSession.shared.dataTask(with: request) { (data, response, error) iOS:来自 URLSession.shared.dataTask 的数据(带有:url 始终为零(在 xcode 调试器中显示 0 字节错误?) - iOS: Data from URLSession.shared.dataTask(with: url is always nil (display 0 bytes bug in xcode debugger?) 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM