How do I check the current progress of URLSession.dataTaskPublisher?

Regarding getting progress from this publisher, looking at the source code, we can see that it’s just doing a completion-block-based data task (i.e. dataTask(with:completionHandler:)). But the resulting URLSessionTask is a private property of the private Subscription used by DataTaskPublisher. Bottom line, this publisher doesn’t provide any mechanism to monitor progress of the underlying task.

As Denis pointed out, you are limited to querying the URLSession for information about its tasks.


I mostly agree with @Rob, however you can control state of DataTask initiated by DataTaskPublisher and its progress by using of URLSession methods:

func downloadData(_ req: URLRequest) {
    URLSession.shared.getAllTasks { (tasks) in
        let task = tasks.first(where: { (task) -> Bool in
            return task.originalRequest?.url == req.url
        })

        switch task {
        case .some(let task) where task.state == .running:
            print("progress:", Double(task.countOfBytesReceived) / Double(task.countOfBytesExpectedToReceive))
            return
        default:
            self.cancelToken = URLSession.shared.dataTaskPublisher(for: req).sink { /* ... */ }
        }
    }
}

Tags:

Swift

Combine