Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. URL / URLComponents / URLSession

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 / MethodDescription
URL(string:)Creates a URL from a string (failable initializer).
URLComponentsA class for decomposing and assembling a URL into its components (scheme, host, path, query, etc.).
URLSession.sharedThe shared URLSession instance.
URLSession.data(from:)An async method that fetches data from a URL (Swift Concurrency).
HTTPURLResponseA 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 .