Swift API Fetching with SwiftUI.
Course Title: Swift Programming: From Basics to Advanced Development Section Title: Networking and Data Persistence Topic: Create an application that fetches data from an API and displays it in the UI.(Lab topic)
Introduction
In this lab topic, we'll explore how to create a Swift application that fetches data from an API and displays it in the user interface. We'll cover the essential steps, from setting up the API request to parsing the response and displaying the data in a SwiftUI view.
Step 1: Choose an API
For this lab, we'll use the JSONPlaceholder API, a free online REST service that provides a simple API for testing and prototyping. You can choose any other API that provides a JSON response.
- API Endpoint:
https://jsonplaceholder.typicode.com/todos
- API Documentation: JSONPlaceholder API Documentation
Step 2: Set up the API Request
To make an API request in Swift, we'll use the URLSession
class. First, create a new Swift file called APIService.swift
and add the following code:
import Foundation
class APIService {
let url = "https://jsonplaceholder.typicode.com/todos"
func fetchTodos(completion: @escaping ([Todo]) -> Void) {
guard let url = URL(string: url) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error fetching todos: \(error.localizedDescription)")
return
}
if let data = data {
do {
let todos = try JSONDecoder().decode([Todo].self, from: data)
completion(todos)
} catch {
print("Error parsing todos: \(error.localizedDescription)")
}
}
}.resume()
}
}
struct Todo: Codable {
let id: Int
let title: String
let completed: Bool
}
This code defines a APIService
class that has a single method fetchTodos
, which makes a GET request to the API endpoint and parses the response into an array of Todo
structs.
Step 3: Create a SwiftUI View
Create a new SwiftUI file called TodosView.swift
and add the following code:
import SwiftUI
struct TodosView: View {
@State private var todos: [Todo] = []
@State private var errorMessage: String = ""
var body: some View {
List(todos) { todo in
VStack(alignment: .leading) {
Text(todo.title)
Text("Completed: \(todo.completed ? "Yes" : "No")")
}
}
.onAppear {
APIService().fetchTodos { todos in
self.todos = todos
}
}
}
}
This code defines a TodosView
struct that displays a list of Todo
items. The onAppear
modifier is used to call the fetchTodos
method when the view appears.
Step 4: Display the View
Create a new SwiftUI scene called ContentView.swift
and add the following code:
import SwiftUI
struct ContentView: View {
var body: some View {
TodosView()
}
}
This code defines a ContentView
struct that simply displays the TodosView
.
Run the App
Run the app on a simulator or physical device. You should see a list of to-do items fetched from the API.
Conclusion
In this lab topic, we've learned how to create a Swift application that fetches data from an API and displays it in the user interface. We've covered the essential steps, from setting up the API request to parsing the response and displaying the data in a SwiftUI view.
If you have any questions or need help with this lab topic, please leave a comment below. Let's review what we've covered before moving on to the next topic, "Importance of testing in Swift development."
Images

Comments