简体   繁体   中英

Get Current Progress from URLSession.shared.dataTask

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

Add URLSessionDownloadDelegate , create a URLSession with delegate

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 .

  1. Data tasks send and receive data using NSData objects. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM