Fetching Remote Data With Async/Await In Recent And Older System Versions
It’s finally quite simple to fetch data easily in Swift!
Performing asynchronous tasks has always been part of the game when building applications for Apple systems. Up until not that long ago, closures and completion handlers had been the main way to handle asynchronous code. A -definitely better- alternative came with the arrival of the Combine framework and its declarative API, where series of operators creating pipelines have been offering a different approach. But the real revolution in my humble opinion actually occurred in Swift with the async/await pattern, which literally transformed the way we write asynchronous code.
The entire async/await concept introduced in WWDC21 constitutes a big, but relatively easy chapter that is really worth the time to study. It’s the future in dealing with asynchronous work in Swift, so adopting it is not a matter of “if”, but “when”. With that in mind, I’m focusing on a quite specific technique in this post; how to fetch data from a remote server using async/await.
At the time of writing this post, the major version on iOS is 15, and on macOS is 12. There are specific new available APIs that make remote data fetching feel like a breeze. But (there is always a “but”) even though async/await has been made available to prior system versions too, these new APIs are not meant to be used there.
The good news in such cases is that we can still put async/await pattern in motion and use it with the old-friends completion handlers. Doing so, as well as demonstrating how to fetch data in the most recent system versions, is what comes next in the post.
Preparing for data fetching
For the purposes of this post, the remote data will be cat facts taken from here. Visiting this link will take you to a page with sample data similar to what we’re going to get. In order to easily convert the fetched JSON data into values that we can use into a program, we’ll start by defining the following struct, which conforms to