Photo by Youssef Sarhan on Unsplash

I have been writing Swift for the last couple of years. Recently I started my SwiftUI journey. My first question was how to do networking with Combine in SwiftUI. After trying different solutions, I came up with an acceptable version that fits my needs. Since this could benefit new users I thought I would dedicate an article on the subject.

To start we create a NetworkEnvironment enum that can hold our different endpoints. For this example, we will consume the open weather API.

To keep everything type-safe we are also introducing a NetworkRoute protocol that will describe our different routes and parameters we would need and a NetworkMethod enum that should speak for itself.

Yay for type-safety

Default the headers to nil so we don’t have to re-implement it in all our routes

We extend the protocol with a method that will create a URLRequest based on the configured properties. I’m aware of the force-unwrap, I would expect it to crash when it is not valid since it would indicate a developer error.

Since we want to display a state to the user whenever something happens we introduce a Resource enum that can hold three basic states.

Loading

Success

Error

We can update our view while our network request is running to any of the above three states.

Now it’s time to introduce Combine we almost have all the pieces of the puzzle to start making requests. Let’s finish it by creating our Network protocol.

We can fetch anything that conforms to Decodable

We also extend this protocol and add a method that will fetch any Decodable from a given NetworkRoute we wrap the whole in a Resource and publish that on our stream.

Finally, it is time to implement our OpenWeather API. Let’s start off by defining our OpenWeatherNetwork struct and implement the routes in OpenWeatherRoute that we want support for.

Customize the decoder to fit your needs

Do not forget to fill in a city and a correct appId

To start making network requests we are going to create a ViewModel that can be observed from SwiftUI. We are going to introduce a NetworkViewModel protocol.

Now we have a base to create our actual WeatherViewModel.

We inject the network, set the NetworkResource alias and specify the route

We then create and pass our ViewModel as an EnvironmentObject and implement it in our SwiftUI view.

And that’s a wrap! I will leave the creation of a Model conforming to Decodable and initialization of the ViewModel as an exercise to the reader.

Here at Pinch, we continue experimenting with SwiftUI to make our apps even better. Do you have any questions or remarks? Let us know in the comments.