Operation-based networking with modern URLSession
updated about 1 year ago; latest suggestion about 1 year ago
URLSession API is designed so you, as developer, don‘t need to care much about it: you hand it off your URLRequest and simply wait for results in the
completionHandler, with no control over the actual process. URLSession framework will internally handle network queue, concurrency and what not.
The good side of Apple's design is that they can implement support for modern protocols with almost zero impact to developers code (AKA platform developer's dream).
For occasional downloads in your app, this is all fine. But if your app is highly-network dependent – say for sports betting, price checking, online shopping etc – that's hardly enough.
- You will have multiple networking calls initiated at the same time.
- You will have inter-dependent network requests.
- You'll need to cancel subsequent requests when something breaks. etc.
If you wait until the request is done in order to cancel it, you will waste resources and your app's UI will be ridden with please-wait spinners. Thus you need to forget about
completionHandler form of URLSessionDataTask and switch to
URLSessionDelegate form, where you have more control and you can make process decisions when header fields are received, as the the body chunks are coming-in etc.
Challenge: now that you have the power to cancel or stop the request mid-flight, how can you make your requests inter-dependent? Before you start employing your Swift-superhero powers of Futures and Promises and Result types to solve this problem, take a step back.
Queueing and inter-dependence of atomic work items is nothing new, it's probably as old as computers are. Thus it's no wonder that Cocoa's Foundation already offers really good tool to tackles these challenges:
Problem: URLSession in Delegate form & Operation(Queue) – these two are next to impossible to use together.
In this talk I will explain the essential differences in design of both APIs and present an approach that bridges these two worlds together for superior networking stack.
This sounds like a really interesting proposal. As someone who makes extensive use of
NSURLSessionI’ve never really found a way to mingle these. I’d love to see your solution.