It’s not uncommon to have alerts in your app and every developer implements showing alerts in some way. I want to share my approach to showing them when app’s architecture is MVVM.
For binding let’s use Bond framework.
Let’s create simple alert model which will be a view model of UIAlertController.
You can also add some extra properties if you need, that model is just for my approach explanation.
Now when we have the model we want to build it’s view representation consistently, so we create new class called AlertBulder.
And again, you can add here your extra logic in builind an alert from a model.
Helpful protocols and extensions
Now we want all controllers marked as AlertPresentableView, to have a method that will bind to its model’s alertModel changes and show up the desired alert controller.
And AlertPresentableViewModel is:
Now we have all the thing set up. Let me show you how to use them.
Supppose we have a view controller which we want to show alerts. The view controller will look like this:
And its view model like this:
That’s all. Build and run and you will see your alert.
The main benefit of this approach is that you have all alert handling logic in your view model.
GitHub link on the project: