iosswiftresturlsession

URLSession across different REST endpoints for the same server


I have an app that makes a whole bunch of different REST calls to the same server from a bunch of different view controllers. What’s best practice with regard to URLSession: Share the same URLSession object? Or just the URLSessionConfiguration object? Or doesn’t matter about either?

For example, when making request to an endpoint, should I

  1. Instantiate a brand new URLSession each request with with the shared URLSessionConfiguration?

  2. Instantiate a single URLSession once for the current active app instance, and reuse it across all requests?


Solution

  • It is not best practice to create multiple URLSessions. Apple recommends creating only one if possible:

    WWDC2017 Advances in Networking, Part 2

    "We have seen developers that take their old NSURLConnection code and convert it to the new URLSession code by mechanically making a URLSession for every old NSURLConnection they used to have. This is very inefficient and wasteful. For almost all of your apps what you want to have is just one URLSession, which can then have as many tasks as you want. The only time you would want more than one URLSession is when you have groups of different operations that have radically different requirements. And in that case you might create two different configuration objects and create two different URLSessions using those two configuration objects."

    Though the Apple developer presenting this session was answering a slightly different question, clearly the answer he gives is good for your question too.