We’ll guide you on how to extract information from a remote JSON file and present it in a list form using SwiftUI.
Before diving in, ensure you have Xcode 11 and MacOS Catalina installed. Both can be downloaded from Apple’s developer portal.
Initiating Your Xcode Project
Start by launching Xcode. You can either click “Start a new Xcode project” on the Xcode welcome screen or go to “File > New > Project.”
In the template selector, opt for iOS as your platform and pick the Single View App template. Click on the Next button, type “SwiftUIJSONListGuide” for the product name, ensure “Use SwiftUI” is selected, then press Next again. Decide where you’d like to save your project on your Mac.
Accessing Sample JSON Information
For this tutorial, you’ll need a sample JSON file named todo. Find it at jsonplaceholder.typicode.com/todos. The JSON file looks something like:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
// ...
]
To display in the List, we’ll make use of the “title” and “completed” attributes.
Outlining Your Information Model
Within Xcode’s project navigator, mouse click on ContentView.swift. Above the ContentView structure, introduce a new structure, Todo, to represent the data model:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
// ...
]
This structure aligns with the Codable protocol, simplifying the decoding of the model from the JSON file, and the Identifiable protocol, making listing of items a breeze.
Retrieving and Refreshing Information
class FetchToDo: ObservableObject {
@Published var todos = [Todo]()
init() {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos")!
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
if let todoItems = data {
let interpretedData = try JSONDecoder().decode([Todo].self, from: todoItems)
DispatchQueue.main.async {
self.todos = interpretedData
}
} else {
print("No data")
}
} catch {
print("Error")
}
}.resume()
}
}
The @Published property will alert you about any changes to refresh the list in ContentView. A task is crafted to fetch the JSON file’s contents. The data gets decoded into an array of Todo items and assigned to the todos property.
Presenting Information with SwiftUI
Modify ContentView to showcase the acquired data:
struct ContentView: View {
@ObservedObject var fetcher = FetchToDo()
var body: some View {
VStack {
List(fetcher.todos) { task in
VStack(alignment: .leading) {
Text(task.title)
Text("\(task.completed.description)")
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
The @ObservedObject property tracks alterations within the FetchToDo class. A list is formulated which consists of the task items. The list showcases the fields “Title” and “Completed.”
App Preview
Within Xcode, head to the Preview panel and click the “Live Preview” option. The sneak peek should mirror the desired outcome.
Wrapping Up
From this tutorial, you’ve gained insights on how to fetch and present JSON data in a list using SwiftUI. It’s an essential skill for crafting dynamic, data-driven apps featuring a sleek and up-to-date user interface. Here’s to smooth coding!