Component - GET request with async/await
This UI component shows how to fetch data from the internet using a GET request with Swift's async/await. It displays the fetched text on the screen and has a button to start the request.
This UI component shows how to fetch data from the internet using a GET request with Swift's async/await. It displays the fetched text on the screen and has a button to start the request.
VStack ├── Text └── Button
async keyword indicate in a Swift function that performs a GET request?async keyword means the function runs asynchronously, allowing other code to run while waiting.async can be called with await to pause until the result is ready without blocking.try await with URLSession.shared.data(from:) to get data and response.(Data, URLResponse), so unpacking with (data, _) is correct if response is unused.func fetchData() async {
let url = URL(string: "https://example.com/data.json")!
do {
let (data, _) = try await URLSession.shared.data(from: url)
print("Data length: \(data.count)")
} catch {
print("Failed to fetch")
}
}try await returns data and response without throwing an error.func load() async {
let url = URL(string: "https://api.example.com")!
let (data, response) = URLSession.shared.data(from: url)
print(String(data: data, encoding: .utf8) ?? "No data")
}data(from:) is async and must be awaited with await.URLSession.shared.data(from: url) without await, causing a compile error.struct User: Decodable {
let id: Int
let name: String
}
func fetchUser() async throws -> User {
let url = URL(string: "https://api.example.com/user")!
// Which code goes here?
}try await URLSession.shared.data(from: url) which returns data and response.JSONDecoder().decode(User.self, from: data) to convert JSON bytes into the User struct.Pass the test and this pattern moves unknown