0
0
iOS Swiftmobile~5 mins

Why API integration connects to servers in iOS Swift

Choose your learning style9 modes available
Introduction

API integration connects your app to servers so it can get or send data. This lets your app show fresh information or save user actions online.

When your app needs to show weather updates from the internet.
When users log in and their info is checked on a server.
When your app sends messages or posts to a social media platform.
When your app downloads images or files stored on a server.
When you want to keep user data synced across multiple devices.
Syntax
iOS Swift
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
  if let data = data {
    // process data
  }
}
task.resume()
Use URLSession to create a task that talks to the server.
Always call resume() to start the task.
Examples
This example fetches user data from a server and prints it as text.
iOS Swift
let url = URL(string: "https://api.example.com/users")!
URLSession.shared.dataTask(with: url) { data, _, _ in
  if let data = data {
    print(String(data: data, encoding: .utf8) ?? "No data")
  }
}.resume()
This example sends data to the server using a POST request.
iOS Swift
guard let url = URL(string: "https://api.example.com/post") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "name=John".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, _ in
  if let data = data {
    print(String(data: data, encoding: .utf8) ?? "No response")
  }
}.resume()
Sample App

This app fetches a to-do item from a server and shows it as text on the screen.

iOS Swift
import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    fetchData()
  }

  func fetchData() {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }
    URLSession.shared.dataTask(with: url) { data, response, error in
      if let data = data, let todo = String(data: data, encoding: .utf8) {
        DispatchQueue.main.async {
          let label = UILabel(frame: CGRect(x: 20, y: 50, width: 300, height: 100))
          label.numberOfLines = 0
          label.text = todo
          self.view.addSubview(label)
        }
      }
    }.resume()
  }
}
OutputSuccess
Important Notes

API calls happen in the background so the app stays responsive.

Always check for errors when connecting to servers.

Use the main thread to update the user interface after getting data.

Summary

API integration connects your app to servers to get or send data.

This helps your app show live info or save user actions online.

Use URLSession in Swift to make these connections safely and smoothly.