In this series, you build a modern networking layer for a Swift application using Foundation's URLSession API. We cover a range of topics, basic and more advanced, from making a simple GET request to signing requests with an access token. We make use of generics and protocol-oriented programming to create a networking layer that is flexible, testable, and easy to extend.
We start this series by making a simple GET request to the mock API to fetch the list of episodes. We won't be using a third party library. One of the goals of this series is to show you how to build a modern networking layer that relies on Foundation's URLSession API. It is simpler than you might think.
Handling errors is one of the less enjoyable aspects of software development, but it is an important one. You don't want to show the user a cryptic error message when something goes wrong, or worse, no error message. There is no clear-cut recipe you can follow. Every project is different. The good news is that error handling is built into Swift and the Combine framework. Let me show you how we can improve the code we wrote in the previous episode.
Even though there is nothing inherently wrong with a view model performing network requests, it isn't an approach I recommend. Moving the networking logic out of the view model has a number of benefits. It reduces code duplication, facilitates unit testing, and improves the maintainability of the project to name a few.
Because the application will interface with a number of endpoints of the mock API, we need to make sure the API client is easy to extend. The more we can reduce code duplication, the easier it is to extend and maintain the API client. In this episode, I show you how to use generics to make the API client extensible and easy to maintain.
The user needs to be signed in to watch a video so the next feature we implement is the ability for the user to sign in with their email and password. This episode illustrates how a proper foundation can save time and reduce complexity. The improvements we made in the previous episode simplify the changes we need to make in this and the next episodes.
Earlier in this series, we declared the computed message property in the APIError enum. While that seemed like a good idea at that time, the previous episode showed that we need a solution that is more flexible. The APIError enum doesn't have the context it needs to define a human-readable message for each of its cases.