SwiftUI | Fetch JSON data & display it into a list
Learn how to create an API call to get data from a remote JSON file and display this data in a SwiftUI list. Let’s get started!
Difficulty: Beginner | Easy | Normal | Challenging
Environment : Xcode 12 & SwiftUI
Start a new Xcode project
Open Xcode > Create a new Xcode project > App template > Call it userJSON and select SwiftUI interface and lifecycle.
Get the online API
Go to the JSONPlaceholder website, we are going to use this JSON URL to display the data in our list. As you can see, it’s a set of 10 elements containing an array of data.
Create the Model
Go ahead and create a Swift file called userModel and copy/paste the following code into it:
This is the structure we are going to use for our app. The id, username, and name will correspond to the ones present in the JSON file. Feel free to add more such as email, phone, website, etc…
Create the ViewModel
Now, we are going to create the file to make API calls between our app and the JSON file, decode it and grab the data. Create the other Swift file, this time call it userViewModel and paste in the code below:
Let’s present these users!
A little trick:
Before building the user interface, it’s worth checking to see if the API call has been made correctly. I recommend you to make the call right now with the onAppear() method. Write the state variable to make the connection between our ContentView and the View. Place the onAppear() method right after the text.
@State var users: [User] = []
.onAppear {
apiCall().getUsers { (users) in
self.users = users
}
}
Run the application and you should have the print in your console such as follow:
As you can see, the debugger is printing all the users, with id, name, and surname, meaning that we are good to go!
To display all the users in a list, replace the current Text with the List such as following:
Run your app 🏃♂️
Now, run your app and you will see the list of users:
Conclusion:
Thanks for reading! Decoding a remote JSON using Swift only takes a few lines of code and building the user interface with SwiftUI is a breeze! For your project, make sure to use the correct format in your model corresponding with the JSON file, as this is a common error.
I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link.