Network Requests With SwiftUI

GET Method — single piece of data

Bathiya Seneviratne
5 min readJun 12, 2021

Modern web and mobile apps rely heavily on network queries. Every major smartphone app is linked to the internet in some way. As a result, learning how to connect our mobile apps to the outside world is important.

I’ll show you how to use SwiftUI to retrieve data from a third-party API in this demonstration. Using the MVVM design pattern, I’ll explain everything from the ground up in a straightforward manner. This article will show you how to retrieve a single piece of data from the API. So, without further ado, let’s get started!

In this tutorial, we’ll using https://jsonplaceholder.typicode.com as our API. The resource panel below can be found by scrolling down.

https://jsonplaceholder.typicode.com

When you visit the /users URL, you will be presented with a list of users. However, in this case, we’ll only be retrieving information for a single user. As a result, we must change the url as shown below.

https://jsonplaceholder.typicode.com/users/1

It will now only show the data of a single user, as shown below.

JSON Response for the https://jsonplaceholder.typicode.com/users/1

Let’s get started on our SwiftUI app with Xcode.

1. Create a new project and call it whatever you like and save it.

2. Organizing the MVVM design pattern’s folder structure

Since we are using the MVVM design pattern in our project it’s better to organize the folder structure first. Inside my app, I’m going to make the following three directories.

  1. View
  2. Model
  3. View Model
MVVM project structure.

I’m going to make a little change to our files right now. I’ll drop my ContentView swift file into the View folder with a drag and drop.

ContentView inside the View folder

Now we are good to go

3. Creating a Data Model

This is a critical component. In our JSON response, we need to collect the key-value pairs. For this task, we can use the POSTMAN software. However, in order to keep things simple, I’ll use the response from my Safari browser that I got previously.

JSON Response for single user

You can see all of the key-value pairs in this JSON response if you look closely. Some have Integer values, while others have String values. With the address and company properties, there are also some nested values presented.

Within the Model folder, we must now create our data model. It should be a swift file. NOT SWIFTUI File. I’m going to call my model as User but you are free to use whatever name you want.

User Model inside the Model folder

Inside the User model, I’ll create several nested structures for address and company characteristics, all of which must follow the Decodable protocol.

Completed code of User model

Now we need to develop a mechanism for getting data from the API, so we’ll use our ViewModel to do so.

3. Creating a ViewModel to Retrieve Information from the API

The task I’ll be doing can be done in a variety of ways. However, the goal of this tutorial is to teach you a basic understanding of the data retrieval process, therefore we’ll write our data retrieving functions inside the ViewModel file to keep things simple.

We must create a new Swift file called UserViewModel inside the View Model folder. As with the view model file, you can choose any name.

Before we begin coding our view model, I’ll go through all of the code pieces that make up our view model.

We must create a Class that follows the ObservableObject protocol within the view model.

We must create an optional variable with the @Published property wrapper inside the class, and its type must be the same as our data model.

Then, within our class, we must create a function to retrieve data from the API (This will perform using the URLSession).

If data is available, we must use the JSONDecoder to decode the response data from the API.

Finally, we must use the Dispatch queue to assign our data to the variable we created in the previous step.

We can now quickly access any attribute within the user variable. However, we can unwrap the values inside our user variable and access them individually for additional safety.

It’s always good have some additional safety.

For this tutorial, I’ll use the data below to display in my app.

  1. name
  2. city
  3. company name

To identify all of the previously described code blocks, see the image below.

Completed code of UserViewModel

Now only thing left is display data in the mobile app.

4. Display data in the mobile app

We must build an Object of our ViewModel with the@ObservedObject property wrapper in the ContentView file. The desired properties of the User object can now be accessed quickly.

In this tutorial, we’ll use the properties of name, city, and company name.

To display all of the data, we’ll first create a VStack and then a couple HStacks within it. You are free to design your UI.

Finally, the VStack view must use the.onAppear() view modifier and call the load data function there.

This is what the ContentView code should look like.

Completed code of ContentView

Finally, in the info.plist, we must enable arbitrary loads under App Transport Security Settings. Allow it to YES.

Now it’s time to test our app in a simulator

GitHub Repository for this project can be download here.

--

--

Bathiya Seneviratne
Bathiya Seneviratne

Written by Bathiya Seneviratne

AI Researcher · Data Enthusiast · Educator · Robotic enthusiast · Software Engineer

No responses yet