Handling Data Download Backpressure in URLSession

I am developing an application that processes a video file stored on a server. I use URLSessionDataTask with a delegate handler to download the file.

It is not necessary to download the entire file at once. Instead, I can load small chunks of the file as needed. This approach helps minimize memory consumption.

I am trying to design a network layer that supports this behavior. Ideally, I would like to have an interface similar to:

func readMoreData(length: Int) async throws -> Data

Problems I Encountered:

It seems that URLSessionDataTask does not allow controlling how many bytes will be downloaded. It always downloads the entire request.

  • If I call suspend on URLSessionDataTask, the network activity does not stop, and the file keeps downloading.
  • If I upgrade the dataTask to a StreamTask, the file still downloads, though reading bytes can be done through the StreamTask API.

I would prefer behavior similar to AsyncHTTPClient (a Swift Server library) or Network Framework. These frameworks allow controlling the number of bytes downloaded at a time. Unfortunately, they do not fit the specific requirements of my project.

Am I correct in understanding that controlling the download process is not possible with URLSessionDataTask?

As a possible solution, I am considering using HTTP Range Requests, though this would increase the number of additional server requests, which I would like to avoid.

Handling Data Download Backpressure in URLSession
 
 
Q