I need to get current progress (received and total bytes) of the data task for GET request to make a progress loading indicator from this data.
Asked
Active
Viewed 2,832 times
-9
-
1So do that. The data task gives you a Progress object for this purpose. https://developer.apple.com/documentation/foundation/urlsessiontask/2908821-progress – matt Mar 01 '19 at 13:43
2 Answers
0
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)
}

Mahdi
- 31
- 1
- 5
-4
There are three types of session tasks. This is copied from Apple's website link.
- Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server.
- 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.
- 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.

Hobbes the Tige
- 3,753
- 2
- 22
- 21
-
Isn't his question about how to get a progress indicator from URLSession? – El Tomato Mar 01 '19 at 13:49
-
Here's another link that can step you through it: https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_from_websites – Hobbes the Tige Mar 01 '19 at 13:50
-
No, his question is how to get progress updates. He is currently using a data session and he should be using a download session with delegate methods (as my answer states). – Hobbes the Tige Mar 07 '19 at 13:27