|
| 1 | +// |
| 2 | +// URLSession.swift |
| 3 | +// HTTP |
| 4 | +// |
| 5 | +// Created by Alsey Coleman Miller on 10/1/25. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +#if canImport(FoundationNetworking) |
| 10 | +import FoundationNetworking |
| 11 | +#endif |
| 12 | +import HTTPTypes |
| 13 | + |
| 14 | +extension URLSession: URLClient { |
| 15 | + |
| 16 | + public func data( |
| 17 | + for request: URLRequest |
| 18 | + ) async throws(Foundation.URLError) -> (Data, URLResponse) { |
| 19 | + do { |
| 20 | + #if canImport(Darwin) |
| 21 | + if #available(macOS 12, iOS 15.0, tvOS 15, watchOS 8, *) { |
| 22 | + return try await self.data(for: request, delegate: nil) |
| 23 | + |
| 24 | + } else { |
| 25 | + return try await _data(for: request) |
| 26 | + } |
| 27 | + #else |
| 28 | + return try await _data(for: request) |
| 29 | + #endif |
| 30 | + } |
| 31 | + catch { |
| 32 | + guard let urlError = error as? Foundation.URLError else { |
| 33 | + assertionFailure("Invalid error \(error)") |
| 34 | + throw URLError(.unknown) |
| 35 | + } |
| 36 | + throw urlError |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +internal extension URLSession { |
| 42 | + |
| 43 | + func _data(for request: URLRequest) async throws -> (Data, URLResponse) { |
| 44 | + try await withCheckedThrowingContinuation { continuation in |
| 45 | + let task = self.dataTask(with: request) { data, response, error in |
| 46 | + if let error = error { |
| 47 | + continuation.resume(throwing: error) |
| 48 | + } else { |
| 49 | + continuation.resume(returning: (data ?? .init(), response!)) |
| 50 | + } |
| 51 | + } |
| 52 | + task.resume() |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#if canImport(HTTPTypesFoundation) |
| 58 | +import HTTPTypesFoundation |
| 59 | + |
| 60 | +extension URLSession: HTTPClient { } |
| 61 | +#endif |
0 commit comments