0
0
Ios-swiftHow-ToBeginner ยท 4 min read

How to Make API Call in Swift: Simple Guide with Example

To make an API call in Swift, use URLSession to create a data task with a URL request. Then, handle the response asynchronously inside the completion handler to process data or errors.
๐Ÿ“

Syntax

Use URLSession.shared.dataTask(with: URL) to start an API call. Inside the completion handler, you get data, response, and error. Always check for errors and unwrap data safely.

swift
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
  if let error = error {
    print("Error: \(error.localizedDescription)")
    return
  }
  guard let data = data else {
    print("No data received")
    return
  }
  // Process data here
}
task.resume()
๐Ÿ’ป

Example

This example fetches JSON data from a public API and prints the raw JSON string. It shows how to start the task and handle the response on a background thread.

swift
import Foundation

let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!

let task = URLSession.shared.dataTask(with: url) { data, response, error in
  if let error = error {
    print("Error: \(error.localizedDescription)")
    return
  }
  guard let data = data else {
    print("No data received")
    return
  }
  if let jsonString = String(data: data, encoding: .utf8) {
    print("Received JSON: \(jsonString)")
  }
}

task.resume()

// Keep the playground running to wait for async call (only needed in playgrounds)
Output
Received JSON: {"userId":1,"id":1,"title":"delectus aut autem","completed":false}
โš ๏ธ

Common Pitfalls

  • Forgetting to call task.resume() means the API call never starts.
  • Not handling errors or unwrapping optionals safely can crash your app.
  • Trying to update UI directly inside the completion handler without switching to the main thread causes UI bugs.
swift
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
  // Wrong: updating UI directly here
  // DispatchQueue.main.async { update UI } is needed
}
// Missing task.resume() means no request is sent
๐Ÿ“Š

Quick Reference

Tips for API calls in Swift:

  • Always call task.resume() to start the request.
  • Check for errors before processing data.
  • Use DispatchQueue.main.async to update UI after receiving data.
  • Use URLSession.shared for simple requests.
โœ…

Key Takeaways

Use URLSession.shared.dataTask with a URL to make API calls in Swift.
Always call task.resume() to start the network request.
Handle errors and unwrap data safely inside the completion handler.
Update UI only on the main thread using DispatchQueue.main.async.
Test API calls with simple JSON endpoints to understand the flow.