get progress from dataTaskWithURL in swift

You can simply observe progress property of the URLSessionDataTask object.

Example:

import UIKit

class SomeViewController: UIViewController {

  private var observation: NSKeyValueObservation?

  deinit {
    observation?.invalidate()
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
    let task = URLSession.shared.dataTask(with: url)

    observation = task.progress.observe(\.fractionCompleted) { progress, _ in
      print("progress: ", progress.fractionCompleted)
    }

    task.resume()
  }
}

Playground example:

import Foundation
import PlaygroundSupport

let page = PlaygroundPage.current
page.needsIndefiniteExecution = true

let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
let task = URLSession.shared.dataTask(with: url) { _, _, _ in
  page.finishExecution()
}

// Don't forget to invalidate the observation when you don't need it anymore.
let observation = task.progress.observe(\.fractionCompleted) { progress, _ in
  print(progress.fractionCompleted)
}

task.resume()

Leave a Comment