API Call in Swift Part 2
Completion and Error Handling
Improving network call from part 1. Using completions and error handlings.
In part 1, we saw how to make a network or API call in a very basics way. But in this article, we will try to improve a bit the code. We will use some completions, error handling, and a proper view model.
Again, we are not going to use any third party. We will be using all the apple APIs.
I am not showing the decodable model, because it's similar to what it was in part 1. If you wish to see it, you can refer to part 1.
Service Manager
- This time we are creating a service manager separated from our view model.
- This class will contain things related to network calls only.
- We are creating function as static so that, we can access that without creating its object.
- You can see there is a completion of the result, counting data and error. We will handle it while calling this function.
- Also, we have created an enum case to handle the errors.
- Lastly — In my code, you will see spaces before the colon, that's not a good habit, I am trying to change it for the last 2 months. 😇
Weather View Model
- Our view model is making that network call in its initialization.
- We are handling the errors and updating the alert title based on success and failure.
- We made it observable so that we can observe the properties in UI.
Thats it for PART 2
Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer