Operation-based networking with modern URLSession

updated 10 months ago; latest suggestion 10 months 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: Operation and OperationQueue.

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.

Suggestions

  • 8b2f2d3e6553c2b4048b93300959895ab76b4154?size=100x100 8b2f2d3e6553c2b4048b93300959895ab76b4154 suggests 10 months ago

    This sounds like a really interesting proposal. As someone who makes extensive use of NSOperation and NSURLSession I’ve never really found a way to mingle these. I’d love to see your solution.