0
0
iOS Swiftmobile~3 mins

Why GET request with async/await in iOS Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fetch data from the internet without making your app freeze or your code messy?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
URLSession.shared.dataTask(with: url) { data, _, _ in
  if let data = data {
    print(String(data: data, encoding: .utf8) ?? "")
  }
}.resume()
After
let (data, _) = try await URLSession.shared.data(from: url)
print(String(data: data, encoding: .utf8) ?? "")
What It Enables

You can write clean, readable code that fetches data from the internet without freezing your app or getting lost in complex callbacks.

Real Life Example

Fetching user profiles from a server in a social media app smoothly, so the app stays responsive while loading new content.

Key Takeaways

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.