URL / URLComponents / URLSession
Swift's URL, URLComponents, and URLSession let you construct URLs and send/receive HTTP requests. Combined with Swift Concurrency, they enable simple asynchronous networking.
Class Overview
| Class / Method | Description |
|---|---|
| URL(string:) | Creates a URL from a string (failable initializer). |
| URLComponents | A class for decomposing and assembling a URL into its components (scheme, host, path, query, etc.). |
| URLSession.shared | The shared URLSession instance. |
| URLSession.data(from:) | An async method that fetches data from a URL (Swift Concurrency). |
| HTTPURLResponse | A class for accessing the status code and headers of an HTTP response. |
Sample Code
import Foundation
// Create a URL
let url = URL(string: "https://example.com/api/users")!
print("URL: \(url)")
print("Host: \(url.host ?? "none")")
print("Path: \(url.path)")
// Build a URL with URLComponents
var components = URLComponents()
components.scheme = "https"
components.host = "api.example.com"
components.path = "/search"
components.queryItems = [
URLQueryItem(name: "q", value: "Swift"),
URLQueryItem(name: "page", value: "1")
]
if let builtURL = components.url {
print("Built URL: \(builtURL)")
}
// GET request with URLSession
struct Post: Codable {
let id: Int
let title: String
}
func fetchPost(id: Int) async throws -> Post {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return try JSONDecoder().decode(Post.self, from: data)
}
Task {
do {
let post = try await fetchPost(id: 1)
print("Title: \(post.title)")
} catch {
print("Error: \(error)")
}
}
// POST request with URLSession
func postData(to url: URL, body: Data) async throws -> Data {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = body
let (data, _) = try await URLSession.shared.data(for: request)
return data
}
Output
URL: https://example.com/api/users Host: example.com Path: /api/users Built URL: https://api.example.com/search?q=Swift&page=1 Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Notes
Swift Concurrency's URLSession.shared.data(from:) fetches data asynchronously and suspends execution with await until it completes. This is far simpler than the traditional callback-based approach.
When a URL contains special characters (spaces, non-ASCII characters, etc.), use URLComponents to handle percent-encoding automatically. URLSession does not block the main thread by default. However, any UI updates must be performed on the @MainActor or via DispatchQueue.main.
For JSON decoding, see Codable / Encodable / Decodable.
If you find any errors or copyright issues, please contact us.