SwiftUI | Combine & URLSession examples with OpenWeatherAPI
In this post, I brought a weather like app using Combine and URLSession. This time, I tried not to use any external library such as AlamoFire, KingFisher.
What I’m going to show in this post are:
- iOS 15 (iOS 14 can also be deployable when
- Xcode 13.2.1
To begin with
And I would like to share an article that I got some useful ideas from(MVVM with Combine Tutorial for iOS | raywenderlich.com). Especially for this post, I brought some great basic settings from the article. If you are interested, I recommend that you could take time and read it.
First of all, for the ease of managing web data, I made a
WeatherDataManager class. It will get a JSON data from OpenWeather’s server for us and then decode them to
You should know that
- I saved my API key to
APIKeys.plistfor security. Of course it doesn’t ensure my key’s safety from getting hacked but at least prevents api key being uploaded to a public repository by adding the file to
- After it finished fetching the key, it will make a
dataPublisher. The publisher will do the role that returns downloaded data to their subscribers at the moment it completed its task.
- I’m not going to reproduce any data in here. That will be taken care of at which subscribers
sinkthose publishers. Now let’s just decode the JSON data to
CurrentWeatherResponsestruct for further use. You can see the details of
It’s time to make a view model which converts response data(
CurrentWeatherResponse) to the actual data(
CurrentWeather) we can use and delivers data to the view later.
WeatherListViewModel is pretty simple.
- The function
fetchWeatherliterally fetches required data by subscribing
Failpublisher when it occurs error. Otherwise, it will return
CurrentWeatherResponse. By mapping the results to
CurrentWeatherstruct’s init function, we can finally get
- Mapped results will be stored in class’s array property
cityViewSourcein the closure function of
Then let’s look into the view.
- At the list and rows part(
WeatherList), rows are used to present weather informations of cities. When it comes to the icon, they are fetched from OpenWeather’s asset, not local asset.
- Each rows are connected to second view(
CurrentWeatherView) when it’s clicked which presents details of the city’s weather condition such as max/min temp, humidity, air pressure etc.
The other components are actually not difficult to make so I’ll just skip it. If you want to look into the others, see here.
Nothing special in here. As I briefly said before, second view,
CurrentWeatherView presents details of the city’s weather condition such as max/min temp, humidity, air pressure etc.
- It receives view model
CurrentWeatherwhich contains required informations from parent view.
moredoesn’t have any functions here. You can add another view like 5 days forecasts.
Also in here, the other components are actually not difficult to make so I’ll just skip it. If you want to look into the others, see here.