0

I'm using a class ApiHandler to interact with an API, that class uses URLSessions to load Data from a server. In some cases, the Data is large enough to cause a very noticeable delay between starting the task and finishing it.

Here's a small example of how a method of this class could look:

class ApiHandler {
    func downloadImage() async throws -> Data {
        //This is just the first large file I could find
        let url = URL(string: "https://effigis.com/wp-content/uploads/2015/02/DigitalGlobe_WorldView1_50cm_8bit_BW_DRA_Bangkok_Thailand_2009JAN06_8bits_sub_r_1.jpg")!
        var request = URLRequest(url: url)
        
        do {
            let (data, response) = try await URLSession.shared.data(for: request)
            return data
        }
    }
}

Now I can call this method from a view using:

Task {
    let imageData = try await
    apiHandler.downloadImage()
}

And (after a short delay) the data is downloaded and can be displayed. How can I display the progress of the task to a user? I've found some solutions of how to handle this using .progress.observe with URLSessionDataTask but that is not async and I don't know how I would access that observer from outside of the class.

Leo Klaus
  • 73
  • 1
  • 8

0 Answers0