More Development, Less Boilerplate, Easier Refactoring
Developing A Reusable Networking Class
And why writing reusable code is important
I personally know more than a few Swift Developers who find writing networking code boring. “There’s too much boilerplate code,” they say. The good news is there’s something you can do about it.
With a little creativity, you can write a class that you can use to perform networking tasks across your app. In fact, that should read apps because you can use this in any app that needs URLSession and it can even nearly automatically handle JSON Encoding and Decoding using Codable (in part 2).
First, let’s write a pretty standard network call using URLSession.shared.dataTask. Since we’re already here, why don’t we download Medium’s front page like so?
- Create a URL
- Create a request using the URL
- Stub out URLSession.shared.dataTask(with: URLRequest, completionHandler: (Data?, URLResponse?, Error?) -> Void)
- Check for errors
- Downcast the URLResponse to a…