Use async/await with URLSession
Description: Discover how you can adopt Swift concurrency in URLSession using async/await and AsyncSequence, and how you can apply Swift concurrency concepts to improve your networking code.
Async await code make your code linear, so it’s much easier to read.
A simple network call might have multiple contexts. The task is created on whatever queue you’re on. The callback is executed on the session’s delegate queue. And the task it self runs on the task’s queue.
With sync it’s easier to reason about code. It all follows the same linear pattern.
await URLSession.shared.data(_:) suspends execution with blocking.
We can handle errors by throwing when appropriate.
In addition to
data(_:) we can also
Downloads are written to a file. You need to move or delete this file if needed by hand.
You can obtain a task handle to support cancellation. The concurrency task is not related to the data task so it may not cancel it.
You can receive an endpoint’s response body as an async sequence of bytes with
URLSession.AsyncBytes is an
AsyncSequence that we can iterate over to process data in real time.
We can use
bytes.lines to get the response line by line rather than byte by byte. We can process these lines one by one.
FileHandle also has support for async sequences.
URLSession is built on delegate methods to handle challenges. Since we no longer have access to talks, we can pass explicit delegates to async data tasks to handle things like authentication challenges and download progress.
The delegate you pass to a task is retained strongly by the task until the task fails or completes.