Handling Multiple URLSession Tasks Efficiently

Saoud M. Rizwan
2 min readAug 26, 2017

--

During my transition from relying on Alamofire to working with the native URLSession class myself, I’ve come across a fundamental issue with data tasks that Alamofire handles for the developer behind the scenes — creating multiple network requests to the same URL at once. This is actually a pretty common problem; think of a scenario where you’re loading images into table view cells, and the user is scrolling through the cells fast. In this scenario, images that aren’t cached are called to be downloaded in network requests, but what if while an image is being downloaded, it’s requested again and a new data task is assigned to retrieving the same image? Here is a code snippet of how you would efficiently handle this type of problem without making unnecessary network requests:

Now let’s use TaskManager and execute multiple data tasks with the same URL, like so:

TaskManager only really carries out one network request to sameUrl but executes all the specified completion blocks with the same data, response, and error. And if you look at your console, it will show:

Finished network taskExecuting completion blockExecuting completion blockExecuting completion blockExecuting completion blockExecuting completion block

If you look at the network activity in the debugger pane, then that will also prove that all these tasks only really made a network request once.

I tested TaskManager out with setting multiple images from one image URL several times in a row, and the total network activity summed up to be about 20 KB, whereas creating and executing all the network requests simultaneously without TaskManager resulted in using a total of 6 MB of network data.

Let me know if you have any questions or concerns on Twitter @sdrzn.

--

--