API handling in SwiftUI — GET Method — Building a Weather watchOS app (Part 4)

Jany Mai
2 min readMay 18, 2020

--

For the weather app, I will use the OpenWeatherMap API. Okay, Let start

First of all, you need to register an account at OpenWeatherMap you can go to this page and create an account to get the API key. I will share this link in the description.

The Api URL :

api.openweathermap.org/data/2.5/weather?q={cityName}&appid={yourApiKey}

you need to insert

  • {cityName} insert the city name
  • {yourApiKey} insert your API key.

If you are watching my video, I will happy if you guys give me a 1 subscriber. Thanks so much

If you lazy, you can use Demo API from an open weather map. this API always returns a mock result

https://samples.openweathermap.org/data/2.5/weather?q=singapore&units=metric&appid=439d4b804bc8187953eb36d2a8c26a02

Let take a look when you call the GET API what data will return

{
...
"main":{
"temp":279.99,
"feels_like":272.77,
"temp_min":278.15,
"temp_max":281.48,
"pressure":1038,
"humidity":45
},
..
}

We need to parse this data and make your data model from it I need the weather with the temp

struct Weather: Decodable {
var temp: Double?
var humidity: Double?
}

BUT the weather is the child object of Weather response. It is the data of the main so we will define WeatherResponse like this

struct WeatherResponse: Decodable {
let main: Weather
}

So, Weather.swift will look like this

Decodable is a type that it can decode itself from an external representation. external representation means you can call from API, you can read it to know the detail

https://developer.apple.com/documentation/swift/decodable

Go to the services folder; I will create a new file name WeatherService.swift

We have three steps to make it works:

1. We are creating the URL with the API we want to call.

2. Create and start a networking task to call the API.

3. Handle the result return from API

Do you remember, what I shared with you in the last blog that when the View wants to have the data from external service (service), it should call via View Model (MVVM pattern) We haven’t define WeatherViewModel yet, so let do it. Create a file with a name is WeatherViewModel.swift

Now, Let update WeatherView.swift

That great…OKE look excellent finish for today, I hope you like it.

Read Building Weather App for WatchOS

In the next blog, I will introduce to you “How We can Call the POST API”

--

--