Building a COVID19 Tracking App Using SwiftUI and MVVM Design Pattern

In this post, I will use a COVID19 JSON API to build a SwiftUI application using the MVVM Design Pattern.

The first step is to implement the HTTP Client which will be responsible for consuming JSON API. Our client is called “Webservice” and the complete implementation is shown below:

The HTTP client returns an array of Tracking objects. Tracking objects is defined below and they represent the model of the app.

The hospitalized property is nullable/optional since sometimes it is null in the JSON response.

The Webservice above is called from the TrackingListViewModel, which is the View Model representing the screen displaying all the COVID19 tracking data.

TrackingListViewModel is also decorated with ObservableObject which means it can be observed by other objects. It consists of a single property called tracking which is an array of TrackingViewModel objects. The tracking property is using the @Published property wrapper, which means anytime this property is set/assigned it will cause a subscription to fire.

The TrackingViewModel class is defined below:

You might be thinking that what is the point of View Model and why can’t you just return the model to the user interface. Model represents the domain object, which consists of rules, validation and business logic. In this example model (Tracking) is serving more like a DTO (Data Transfer Object) rather than the domain object. In larger applications you will have logic in model objects which should not be exposed to the UI layer.

Finally, ContentView is used to display all the information on the screen. The implementation of ContentView is shown below:

The result is shown below:

COVID19 Tracking App
  1. GitHub
  2. SwiftUI — Declarative Interfaces for Apple Devices

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store