Just saw some code where in a method:
- a NSURLSession is created from a configuration as an automatic
- a dataTask is created by the session, and "resumed"
- method returns
Yikes! In my code I've always created a single session, saved it as an ivar, then gotten and "resumed" dataTasks, only releasing the session when the object is released.
Comments?
Yikes!
Yikes indeed. This is a common anti-pattern, one that we specifically warned against at at WWDC this year. Creating a session per request is inefficient both on the CPU and, more importantly, on the network. Specifically, it prevents connection reuse, which can radically slow down back-to-back requests. This is especially bad for HTTP/2.
We encourage folks to group all similar tasks in a single session, using multiple sessions only if you have different sets of tasks with different requirements (like interactive tasks versus background download tasks). That means that many simple apps can get away with using a single statically-allocated session.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"