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.
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.
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()
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()
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()
This app fetches a to-do item from a server and shows it as text on the screen.
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() } }
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.
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.
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, _, error in
if let data = data {
print(String(data: data, encoding: .utf8) ?? "No data")
} else {
print("Error")
}
}
task.resume()let url = URL(string: "https://api.example.com")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if error != nil {
print("Failed")
} else {
print("Success")
}
}Pass the test and this pattern moves unknown