We use GET requests to ask a server for information. Using async/await makes this easy and clear without blocking the app.
GET request with async/await in iOS Swift
func fetchData() async throws -> Data { let url = URL(string: "https://example.com/data.json")! let (data, _) = try await URLSession.shared.data(from: url) return data }
async means the function runs without blocking the app.
await waits for the network call to finish before continuing.
func fetchText() async throws -> String { let url = URL(string: "https://example.com/text.txt")! let (data, _) = try await URLSession.shared.data(from: url) return String(decoding: data, as: UTF8.self) }
func fetchJSON() async throws -> [String: Any] { let url = URL(string: "https://example.com/info.json")! let (data, _) = try await URLSession.shared.data(from: url) let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] return json ?? [:] }
This SwiftUI app fetches a to-do item from the internet using async/await. It shows the task title on screen or an error message if something goes wrong.
import SwiftUI struct ContentView: View { @State private var message = "Loading..." var body: some View { Text(message) .padding() .task { do { let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! let (data, _) = try await URLSession.shared.data(from: url) if let todo = try? JSONDecoder().decode(Todo.self, from: data) { message = "Task: \(todo.title)" } else { message = "Failed to decode data" } } catch { message = "Error: \(error.localizedDescription)" } } } } struct Todo: Codable { let userId: Int let id: Int let title: String let completed: Bool } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Always check for errors using do-catch when using async/await with network calls.
Use URLSession.shared.data(from:) for simple GET requests.
Remember to update UI on the main thread; SwiftUI's .task modifier handles this automatically.
GET requests ask a server for data.
async/await makes network calls easy and keeps the app responsive.
Use URLSession.shared.data(from:) with await to get data.
Practice
async keyword indicate in a Swift function that performs a GET request?Solution
Step 1: Understand async keyword meaning
Theasynckeyword means the function runs asynchronously, allowing other code to run while waiting.Step 2: Connect async with await usage
Functions markedasynccan be called withawaitto pause until the result is ready without blocking.Final Answer:
The function runs asynchronously and can be awaited. -> Option BQuick Check:
async means asynchronous function [OK]
- Thinking async means synchronous/blocking
- Confusing async with retry logic
- Assuming async only applies to POST requests
Solution
Step 1: Identify correct async/await syntax
The correct syntax usestry awaitwithURLSession.shared.data(from:)to get data and response.Step 2: Check tuple unpacking
The method returns a tuple of(Data, URLResponse), so unpacking with(data, _)is correct if response is unused.Final Answer:
let (data, _) = try await URLSession.shared.data(from: url) -> Option AQuick Check:
Use try await with data(from:) [OK]
- Omitting try keyword
- Using dataTask without await
- Not unpacking the returned tuple
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")
}
}Solution
Step 1: Analyze successful GET request
If the request succeeds,try awaitreturns data and response without throwing an error.Step 2: Understand print statement output
The code prints the length of the received data in bytes, so output is "Data length: [number]".Final Answer:
Data length: [number of bytes in data] -> Option DQuick Check:
Success prints data length [OK]
- Assuming print shows raw data
- Confusing catch block output
- Expecting zero length on success
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")
}Solution
Step 1: Check async call usage
The methoddata(from:)is async and must be awaited withawait.Step 2: Confirm missing await keyword
The code callsURLSession.shared.data(from: url)withoutawait, causing a compile error.Final Answer:
Missing await keyword before URLSession.shared.data(from: url) -> Option CQuick Check:
Async calls require await [OK]
- Forgetting await on async calls
- Assuming try is optional
- Misreading URL validity
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?
}Solution
Step 1: Use async/await with data(from:)
The correct async call istry await URLSession.shared.data(from: url)which returns data and response.Step 2: Decode JSON data into struct
UseJSONDecoder().decode(User.self, from: data)to convert JSON bytes into the User struct.Final Answer:
let (data, _) = try await URLSession.shared.data(from: url) return try JSONDecoder().decode(User.self, from: data) -> Option AQuick Check:
Use try await with data(from:) and decode JSON [OK]
- Using dataTask instead of data(from:)
- Omitting await or try keywords
- Not decoding JSON properly
Ready to prove it?
Pass the test and this pattern moves unknown
