MVVM Design pattern in iOS
First of all, the MVVM design pattern stands for Model View and View Model. Suppose that you have taken two different views with a different User interface that need to be populated with data from the same model class. By using MVVM, you can use data from a single model class and represent it in a different way to populate a view.
Components overview with their roles:-
- Models – Model is simply a structure or class or entity of domain that represents your data. Suppose, if you are building a movie website, then your model might represent a Movie.
- Views – That is something you see on your screen means the UI elements you see on your screen.
- View Models – It obtains information from View Controller, manipulates all this information, and redirects back to VC.
So here how we structure our code and creates the required files in their respective groups. So we have created 4 new files one in each group (ViewController, Models, ViewModels, API Service).
1. Model:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import Foundation import SwiftyJSON struct Employee { var id : String var employee_name : String var employee_age : Int init(data: JSON) { self.id = data["id"].stringValue self.employee_name = data["employee_name"].stringValue self.employee_age = data["employee_age"].intValue } } struct EmployeeModelData { var status: String var data: [Employee] init(data: JSON) { self.status = data["status"].stringValue self.data = data["data"].arrayValue.map{ (Employee(data: $0)) } } } |
2. ViewController:-
First of all the View controller will get called and from the view controller, we will call our ViewModel class.
3. ViewModel:-
ViewModel is the main component of this architecture pattern and never knows what the view is or what the view does. This makes this architecture more testable and removes complexity from the view. In the View Model, we will call our APIService class to fetch data from the server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import Foundation class EmployeeDetailsViewModel : NSObject,ReloadTable{ func reloadTblView() { delegate?.reloadTblView() } public var apiService : ApiServices! var delegate: ReloadTable? override init() { super.init() self.apiService = ApiServices() self.apiService.delegate = self getEmpData() } func getEmpData(){ self.apiService.hitApi() } } |
4. API Service:-
API Service class is a simple class where we are fetching employee data using URLSession or third party library class. You can use any networking model here to fetch data from your server. From our view model class, we will call the API Service class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import Foundation import Alamofire import SwiftyJSON class ApiServices : NSObject{ var delegate: ReloadTable! var object : EmployeeModelData? func hitApi() { AF.request("http://dummy.restapiexample.com/api/v1/employees" , method: HTTPMethod(rawValue: "GET")).responseJSON { response in switch (response.result){ case .success(let datawork): let json = JSON(datawork) self.object = EmployeeModelData(data: json) print(json) if (self.object?.data.count)! > 0 { DispatchQueue.main.async { self.delegate?.reloadTblView() } } case .failure(_): print(response.error ?? "") } } } } protocol ReloadTable { func reloadTblView() } |
Here is the complete flow working:-
1. View controller will get called and the view will have a reference to the ViewModel.
2. The View will get some user action and the view will call ViewModel.
3. ViewModel will request APIService and APIService sends a response back to the ViewModel.
4. Once we receive a response, the View Model notifies the view.
5. The View will update the UI with data.
This is our expected output-
we have a view controller (UI) that needs to fetch data from the server(API) and need to display it in the UI.
Prons and cons:-
Prons:
1. Code reuse: In View-Model class we implement init, set up, and view presentation method, so we use this functionality in each new view controller.
2. Improved Testability: In MVVM we can make all classes separate so we can easily find an error.
3. Reduce code size.
Cons:
1. The MVVM Design pattern is basically used when we work on multiple views but not for a single view application.
Conclusion:
MVVM design patterns are useful for iOS app development. MVVM is a new abstract idea for a design pattern. The View Model is really nice and simple way of separating presentation logic into another entity which helps us to avoid Massive-View-Controller and keep things easier to control and covered with Unit Tests. That is where we go, simple and testable architecture.