Caution

お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。

Swift辞典

  1. トップページ
  2. Swift辞典
  3. URL / URLComponents / URLSession

URL / URLComponents / URLSession

Swiftの『URL』『URLComponents』『URLSession』を使うと、URLの構築とHTTPリクエストの送信・受信を行えます。Swift Concurrency との組み合わせでシンプルな非同期通信が可能です。

クラス一覧
クラス / メソッド概要
URL(string:)URL文字列から URL を生成します(失敗可能イニシャライザ)。
URLComponentsURL をコンポーネント(スキーム・ホスト・パス・クエリ等)に分解・組み立てするクラスです。
URLSession.shared共有の URLSession インスタンスです。
URLSession.data(from:)URL からデータを取得する非同期メソッド(Swift Concurrency)です。
HTTPURLResponseHTTP レスポンスのステータスコードやヘッダーを取得するクラスです。
サンプルコード
import Foundation

// URL の生成
let url = URL(string: "https://example.com/api/users")!
print("URL: \(url)")
print("ホスト: \(url.host ?? "なし")")
print("パス: \(url.path)")

// URLComponents で URL を組み立て
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("組み立てた URL: \(builtURL)")
}

// URLSession で GET リクエスト
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("タイトル: \(post.title)")
    } catch {
        print("エラー: \(error)")
    }
}

// URLSession で POST リクエスト
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
}
実行結果
URL: https://example.com/api/users
ホスト: example.com
パス: /api/users
組み立てた URL: https://api.example.com/search?q=Swift&page=1
タイトル: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
概要

Swift Concurrency の『URLSession.shared.data(from:)』は非同期でデータを取得し、完了を await で待機します。コールバックを使う旧来の方法より遥かにシンプルです。

URLに特殊文字(スペース・日本語など)が含まれる場合は『URLComponents』を使ってパーセントエンコーディングを自動化することを推奨します。URLSession はデフォルトでメインスレッドをブロックしません。ただし UI の更新は @MainActor または DispatchQueue.main で行う必要があります。

JSONのデコードについてはCodable / Encodable / Decodableを参照してください。

記事の間違いや著作権の侵害等ございましたらお手数ですがまでご連絡頂ければ幸いです。