Skip to content

Instantly share code, notes, and snippets.

@aydenp
Last active May 13, 2024 14:17
Show Gist options
  • Save aydenp/dd004b38048195b80e4a6c17078c6de4 to your computer and use it in GitHub Desktop.
Save aydenp/dd004b38048195b80e4a6c17078c6de4 to your computer and use it in GitHub Desktop.
Port URLSession's convenience async methods to Linux
//
// URLSession+LinuxAsync.swift
//
// Created by Ayden Panhuyzen on 2022-11-27.
//
#if canImport(FoundationNetworking)
import Foundation
import FoundationNetworking
public extension URLSession {
/// Convenience method to load data using an URLRequest, creates and resumes an URLSessionDataTask internally.
///
/// - Parameter request: The URLRequest for which to load data.
/// - Returns: Data and response.
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
self.dataTask(with: request) { data, response, error in
if let data = data, let response = response {
continuation.resume(returning: (data, response))
return
}
continuation.resume(throwing: error!)
}.resume()
}
}
/// Convenience method to load data using an URL, creates and resumes an URLSessionDataTask internally.
///
/// - Parameter url: The URL for which to load data.
/// - Returns: Data and response.
func data(from url: URL) async throws -> (Data, URLResponse) {
try await data(for: URLRequest(url: url))
}
}
#endif
//
// URLSession+LinuxAsync.swift
//
// Created by Ayden Panhuyzen on 2022-11-27.
//
#if canImport(FoundationNetworking)
import Foundation
import FoundationNetworking
public extension URLSession {
/// Convenience method to load data using an URLRequest, creates and resumes an URLSessionDataTask internally.
///
/// - Parameter request: The URLRequest for which to load data.
/// - Returns: Data and response.
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
self.dataTask(with: request) { data, response, error in
if let data, let response {
continuation.resume(returning: (data, response))
return
}
continuation.resume(throwing: error!)
}.resume()
}
}
/// Convenience method to load data using an URL, creates and resumes an URLSessionDataTask internally.
///
/// - Parameter url: The URL for which to load data.
/// - Returns: Data and response.
func data(from url: URL) async throws -> (Data, URLResponse) {
try await data(for: URLRequest(url: url))
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment