Design+Code logo

Quick links

Suggested search

Network class

We'll need to create a class that conforms to the ObservableObject protocol. By conforming our class to an ObservableObject, the changes in the class will automatically be reflected in our View. Let's create a Network.swift file, in which we will call the API.

// Network.swift

import SwiftUI

class Network: ObservableObject {

}

User model

Next, we'll create a User model. By doing so, we can conform our variables to a User data type. The model will also allow us to decode the JSON we will get from the API into a User data type. Moreover, we'll be able to call the user's name by simply writing user.name.

First, we'll need to know how the JSON data we get is structured. We can head over to https://jsonplaceholder.typicode.com/users to see how it is structured:

Users endpoint JSON data

As you can see in the image above, the JSON is an array of objects. Each object represents a user, and it contains many key-value pairs.

Back in our project, we'll need to create a struct that contains all of these key-value pairs. Luckily, I already created the User model for you, below. Simply create a new User.swift file, and paste the following code:

// User.swift

import Foundation

struct User: Identifiable, Decodable {
    var id: Int
    var name: String
    var username: String
    var email: String
    var address: Address
    var phone: String
    var website: String
    var company: Company

    struct Address: Decodable {
        var street: String
        var suite: String
        var city: String
        var zipcode: String
        var geo: Geo

        struct Geo: Decodable {
            var lat: String
            var lng: String
        }
    }

    struct Company: Decodable {
        var name: String
        var catchPhrase: String
        var bs: String
    }
}

This model conforms to the Identifiable and Decodable protocols. Identifiable means that each item has a unique ID. Decodable means that it can be decoded - for example, we can transform a JSON object into this data model.

@Published variable

Back in Network.swift, we'll need to create a @Published users variable inside of the class. The variable's type will be an array of Users. We'll initialize the variable with an empty array to begin with.

// Network.swift

class Network: ObservableObject {
		@Published var users: [User] = []
}

Get request

Now, we need to create our getUsers function to fetch the users from the API. Create the function inside of the Network class.

// Network.swift

func getUsers() {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError("Missing URL") }

    let urlRequest = URLRequest(url: url)

    let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if let error = error {
            print("Request error: ", error)
            return
        }

        guard let response = response as? HTTPURLResponse else { return }

        if response.statusCode == 200 {
            guard let data = data else { return }
            DispatchQueue.main.async {
                do {
                    let decodedUsers = try JSONDecoder().decode([User].self, from: data)
                    self.users = decodedUsers
                } catch let error {
                    print("Error decoding: ", error)
                }
            }
        }
    }

    dataTask.resume()
}

In the code above, we are making sure that we have a URL before running the next line of code. With this URL, we are creating a URLRequest, and passing it to our dataTask.

We are making sure that there's no error and that we do get a response back. If the response is 200 Okay, we double check that we have data.

We then decode the data we get, which is JSON format, using JSONDecoder, and decode the data into an array of Users. Once the decoding is done, we assign it to the users variable we defined at the top of the class.

Finally, we are resuming our dataTask with dataTask.resume().

Create an environmentObject

Now that our function is created, we need to add our Network class as an EnvironmentObject in the ProjectNameApp.swift file.

// ProjectNameApp.swift

import SwiftUI

@main
struct ProjectNameApp: App {
    var network = Network()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(network)
        }
    }
}

In ContentView, add Network as an EnvironmentObject.

// ContentView.swift

struct ContentView: View {
		@EnvironmentObject var network: Network

		// More code...
}

To make the preview work, remember to add the environmentObject in your ContentView's preview as well, as the preview is a different entity from the App:

// ContentView.swift

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(Network())
    }
}

Call getUsers

In your body, create a ScrollView and onAppear of it, we'll call our getUsers function:

// ContentView.swift

var body: some View {
		ScrollView {
				Text("All users")
		        .font(.title).bold()
		}
		.onAppear {
				network.getUsers()
		}
}

Iterate over users

Then, simply iterate over network.users. We'll display each user's ID, name, email and phone.

VStack(alignment: .leading) {
    ForEach(network.users) { user in
        HStack(alignment:.top) {
            Text("\(user.id)")

            VStack(alignment: .leading) {
                Text(user.name)
                    .bold()

                Text(user.email.lowercased())

                Text(user.phone)
            }
        }
        .frame(width: 300, alignment: .leading)
        .padding()
        .background(Color(#colorLiteral(red: 0.6667672396, green: 0.7527905703, blue: 1, alpha: 0.2662717301)))
        .cornerRadius(20)
    }
}

If you're using the Preview, remember to press play to fetch the data from the API. The results should instantly appear if you're using the Simulator.

Final code

This is the final code for the Network class:

import SwiftUI

class Network: ObservableObject {
    @Published var users: [User] = []

    func getUsers() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError("Missing URL") }

        let urlRequest = URLRequest(url: url)

        let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if let error = error {
                print("Request error: ", error)
                return
            }

            guard let response = response as? HTTPURLResponse else { return }

            if response.statusCode == 200 {
                guard let data = data else { return }
                DispatchQueue.main.async {
                    do {
                        let decodedUsers = try JSONDecoder().decode([User].self, from: data)
                        self.users = decodedUsers
                    } catch let error {
                        print("Error decoding: ", error)
                    }
                }
            }
        }

        dataTask.resume()
    }
}

This is the final code for ContentView:

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var network: Network

    var body: some View {
        ScrollView {
            Text("All users")
                .font(.title)
                .bold()

            VStack(alignment: .leading) {
                ForEach(network.users) { user in
                    HStack(alignment:.top) {
                        Text("\(user.id)")

                        VStack(alignment: .leading) {
                            Text(user.name)
                                .bold()

                            Text(user.email.lowercased())

                            Text(user.phone)
                        }
                    }
                    .frame(width: 300, alignment: .leading)
                    .padding()
                    .background(Color(#colorLiteral(red: 0.6667672396, green: 0.7527905703, blue: 1, alpha: 0.2662717301)))
                    .cornerRadius(20)
                }
            }

        }
        .padding(.vertical)
        .onAppear {
            network.getUsers()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(Network())
    }
}

This is the final result in the Simulator:

Simulator final result for HTTP Get Request

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Data from JSON

READ NEXT

WKWebView

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Browse all downloads

1

Firebase Auth

How to install Firebase authentification to your Xcode project

8:18

2

Read from Firestore

Install Cloud Firestore in your application to fetch and read data from a collection

8:01

3

Write to Firestore

Save the data users input in your application in a Firestore collection

5:35

4

Join an Array of Strings

Turn your array into a serialized String

3:33

5

Data from JSON

Load data from a JSON file into your SwiftUI application

5:08

6

HTTP Request

Create an HTTP Get Request to fetch data from an API

6:31

7

WKWebView

Integrate an HTML page into your SwiftUI application using WKWebView and by converting Markdown into HTML

5:25

8

Code Highlighting in a WebView

Use Highlight.js to convert your code blocks into beautiful highlighted code in a WebView

5:11

9

Test for Production in the Simulator

Build your app on Release scheme to test for production

1:43

10

Debug Performance in a WebView

Enable Safari's WebInspector to debug the performance of a WebView in your application

1:57

11

Debug a Crash Log

Learn how to debug a crash log from App Store Connect in Xcode

2:22

12

Simulate a Bad Network

Test your SwiftUI application by simulating a bad network connection with Network Link Conditionner

2:11

13

Archive a Build in Xcode

Archive a build for beta testing or to release in the App Store

1:28

14

Apollo GraphQL Part I

Install Apollo GraphQL in your project to fetch data from an API

6:21

15

Apollo GraphQL Part 2

Make a network call to fetch your data and process it into your own data type

6:43

16

Apollo GraphQL Part 3

Display the data fetched with Apollo GraphQL in your View

5:08

17

Configuration Files in Xcode

Create configuration files and add variables depending on the environment - development or production

4:35

18

App Review

Request an app review from your user for the AppStore

5:43

19

ImagePicker

Create an ImagePicker to choose a photo from the library or take a photo from the camera

5:06

20

Compress a UIImage

Compress a UIImage by converting it to JPEG, reducing its size and quality

3:32

21

Firebase Storage

Upload, delete and list files in Firebase Storage

11:11

22

Search Feature

Implement a search feature to filter through your content in your SwiftUI application

9:13

23

Push Notifications Part 1

Set up Firebase Cloud Messaging as a provider server to send push notifications to your users

5:59

24

Push Notifications Part 2

Create an AppDelegate to ask permission to send push notifications using Apple Push Notifications service and Firebase Cloud Messaging

6:30

25

Push Notifications Part 3

Tie everything together and test your push notifications feature in production

6:13

26

Network Connection

Verify the network connection of your user to perform tasks depending on their network's reachability

6:49

27

Download Files Locally Part 1

Download videos and files locally so users can watch them offline

6:05

28

Download Files Locally Part 2

Learn how to use the DownloadManager class in your views for offline video viewing

6:02

29

Offline Data with Realm

Save your SwiftUI data into a Realm so users can access them offline

10:20

30

HTTP Request with Async Await

Create an HTTP get request function using async await

6:11

31

Xcode Cloud

Automate workflows with Xcode Cloud

9:23

32

SceneStorage and TabView

Use @SceneStorage with TabView for better user experience on iPad

3:52

33

Network Connection Observer

Observe the network connection state using NWPathMonitor

4:37

34

Apollo GraphQL Caching

Cache data for offline availability with Apollo GraphQL

9:42

35

Create a model from an API response

Learn how to create a SwiftUI model out of the response body of an API

5:37

36

Multiple type variables in Swift

Make your models conform to the same protocol to create multiple type variables

4:23

37

Parsing Data with SwiftyJSON

Make API calls and easily parse data with this JSON package

9:36

38

ShazamKit

Build a simple Shazam clone and perform music recognition

12:38

39

Firebase Remote Config

Deliver changes to your app on the fly remotely

9:05