0
0
iOS Swiftmobile~5 mins

GET request with async/await in iOS Swift

Choose your learning style9 modes available
Introduction

We use GET requests to ask a server for information. Using async/await makes this easy and clear without blocking the app.

When you want to load user data from a website.
When your app needs to show the latest news or weather.
When fetching images or text from the internet to display.
When you want to update your app content without freezing the screen.
Syntax
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.

Examples
This example fetches plain text from a URL and converts it to a String.
iOS Swift
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)
}
This example fetches JSON data and converts it into a dictionary.
iOS Swift
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 ?? [:]
}
Sample App

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.

iOS Swift
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()
    }
  }
}
OutputSuccess
Important Notes

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.

Summary

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.