[iOS]Covid-19 data App using API

MYH
彼得潘的 Swift iOS App 開發教室
7 min readJul 24, 2021

--

In late 2019, an unknown virus emerged from Wuhan, China, and resulted in a worldwide outbreak. Taiwan was lucky enough to keep the virus at bay for a long duration in spite of limited national resources. Unfortunately, Covid still managed to infiltrate our nation and spread like wild fire in early 2021. And thus, our government was forced to extend to level 3 regulation which forced us to stay at home…

That’s just the background of this article. Anyway… I think it would be a good idea to do an app related to our current issues and also practice Networking API at the same time. So, without further ado, let’s dive in.

As always, here’s a quick demo of my app. (Sorry in advance if the simulator is a little bit laggy, I’m still rockin’ with a 2015 macbook Pro.)

To be short, this app can show you today new cases, total cases, today deaths, and total deaths of Covid-19 in the country which you type in the search field. And also, it will show you the data of new cases in the last 7 days.

API, Parsing JSON

Firs of all, here’s the source of the API. (Thanks to Worldometers and John Hopkins University for these amazing open APIs, which don’t even need an API key)

This website provides so many different URLs and parameters for us to customize. For example:

https://corona.lmao.ninja/v3/covid-19/historical/taiwan

This was the url that I used to fetch JSON data. And it looks like this.

Noted that you probably won’t be seeing the same view as I did. That’s because I’m using “JSON Viewer Pro”, which is a Chrome Website Extension. It helps you visualize the JSON data so that you won’t feel dizzy looking at all those brackets, dots and stats.

Now that’s set up the code to fetch the JSON.

Notes:
1. struct has to follow Decodable protocol. (Or the typealias “Codable”)
2. must set the property as the same name as the key of the JSON data.

And here comes the tricky part. What if our JSON data properties are malleable? What if the keys of the JSON data are not always the same every time you perform a request? What property should we set in the Decodable struct then?

https://corona.lmao.ninja/v3/covid-19/historical/taiwan?lastdays=7

This URL can show us the data in the last 7 days. However, the properties in timeline/cases, as you can see, are the dates of the last seven days. In this case, the keys in this JSON data will change everyday. We can set our decodable struct like below to tackle with this situation.

And the data that got passed in will look like this.

These are the data of the accumulated numbers of the last 30 days. However, what I want are the numbers of the new cases in each day. So, we need to do some alterations.

Now that we’re all set. Let’s take a look at how to perform the request and parse the JSON.

1.we need to set the URL.
func URL(string:)
2.we need to create a URLSession
func URLSession(configuration: .default)
3.give the session a task
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
4.Last but not least, start the task.
func resume()

To decode the JSON, we need a JSON decoder which we can set up by a simple line.
let decoder = JSONDecoder()
and then the decode function.
func decode<T>(_ type: T.Type, from: Self.Input) throws -> T where T : Decodable

After we get the data in our dataTask function’s closure, we want to pass our data to the view controller to update our UI. I initially wanted to use these codes written inside the closure to pass my data to my view controller.

let VC = Covid19ViewController()
VC.UILabel = Data.Something

But then I found out that nothing changed when I was running my project. Nothing got updated. That’s because these lines created a new view controller where all the updates were happening. Thus, I chose another route. And that’s when Protocol Delegate came in.

Protocol Delegate

Let’s take a look at my code.

protocol Covid19ManagerDelegate {func updateData(covid: Covid19Model)}
var delegate: Covid19ManagerDelegate?

And in the view controller. (Remember to set the delegate to self in the view controller’s viewDidLoad().

covid19ManagerDelegate.delegate = selfextension Covid19ViewController: Covid19ManagerDelegate {func updateData(covid: Covid19Model) {DispatchQueue.main.async {self.todayCaesLabel.text = String(covid.todayCinModel)self.totalCasesLabel.text = String(covid.totalCinModel)self.todayDeathsLabel.text = String(covid.todayDinModel)self.totalDeathsLabel.text = String(covid.totoalDinModel)self.countryID.text = covid.idinModelself.countryFlag.sd_setImage(with: URL(string: covid.countryFlag))}}}

I will try my best to explain how protocol and delegate work.

Here we have an example. Let’s say that I created a Rasengan protocol which represents that I can use Rasengan. By writing delegate to other people(rasengan.delegate = self), I let these people learn the rasengan protocol, and they must use the mighty rasengan(func useRASENGAN()) to destroy enemies in battle.

okay… I’ll admit that might not be the best example. I recommnd having a go on the official website.

Or sign up for Dr.Angela’s classes on Udemy

Or find more articles in Medium. (Strongly recommend my teacher, Peter)

CocoaPods Charts

The last part is how I build the chart using the Charts cocoapods.
As always, do the following steps in the terminal to install Charts.

  1. cd to your project directory
  2. pod init
  3. open the pod file in your project folder
  4. pod ‘Charts’
  5. close the Xcode project and run pod install in the terminal
  6. import Charts in your view controller or whatever file you wish to use this library

And now let’s break it down on how to use Charts in Xcode.

After importing Charts in your view controller, create a view on your main.storyboard and subclass it to LinChartView.

Link the view to the view controller and select the LineChartView type.
Once finished all these setting, it’s time to dive in to the codes.

Basically, there are four steps in making your chart.

  1. Set the DataEntry. This is where you will store the values.
  2. Set the DataSet. This is where you can alter the color, font, size, etc.
  3. Set the Data. This is the object that will be added to your view.
  4. Pass the Data to your ChartView.

And here’s my code.

Reference:

And that’s a wrap. Here’s my Github file link. You’re welcome to download it and give it a try. If you find any error, please feel free to correct me in the comment section.

--

--