What if you could fetch data from the internet without making your app freeze or your code messy?
Why GET request with async/await in iOS Swift? - Purpose & Use Cases
Imagine you want to fetch weather data from the internet for your app. You write code that waits for the data to come back before moving on. But the app freezes and becomes unresponsive while waiting.
Using old methods, your app can freeze or lag because it waits for the network response on the main thread. This makes the app feel slow and frustrating. Also, handling callbacks manually can get messy and confusing.
With async/await, you write code that looks simple and clear, but runs in the background without freezing the app. It waits for the data smoothly, then continues once the data arrives, keeping your app fast and responsive.
URLSession.shared.dataTask(with: url) { data, _, _ in if let data = data { print(String(data: data, encoding: .utf8) ?? "") } }.resume()
let (data, _) = try await URLSession.shared.data(from: url) print(String(data: data, encoding: .utf8) ?? "")
You can write clean, readable code that fetches data from the internet without freezing your app or getting lost in complex callbacks.
Fetching user profiles from a server in a social media app smoothly, so the app stays responsive while loading new content.
Old network calls can freeze your app and are hard to read.
Async/await lets you write simple code that runs smoothly in the background.
This makes your app faster and easier to maintain.
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
