Implement backports

This commit is contained in:
Sven Weidauer 2021-11-09 20:46:04 +01:00
parent 55229d9473
commit 6d2751d326
3 changed files with 24 additions and 5 deletions

View file

@ -6,6 +6,7 @@ import PackageDescription
let package = Package(
name: "AsyncBackports",
platforms: [
// TODO: Xcode 13.2 set targets where backport available
.macOS(.v12),
.iOS(.v15),
.watchOS(.v8),

View file

@ -1,4 +1,3 @@
public struct Backport<Original> {
let original: Original
}

View file

@ -5,7 +5,6 @@ public extension URLSession {
}
public extension Backport where Original: URLSession {
/// Convenience method to load data using an URLRequest, creates and resumes an URLSessionDataTask internally.
///
/// - Parameter request: The URLRequest for which to load data.
@ -16,7 +15,23 @@ public extension Backport where Original: URLSession {
@available(tvOS, deprecated: 15.0, message: "No need for .backport any more")
@available(watchOS, deprecated: 8.0, message: "No need for .backport any more")
func data(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) {
if #available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) {
return try await original.data(for: request, delegate: delegate)
} else {
return try await withUnsafeThrowingContinuation { continuation in
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data, let response = response {
continuation.resume(returning: (data, response))
} else if let error = error {
continuation.resume(throwing: error)
} else {
fatalError("Neither response nor error")
}
}
task.delegate = delegate
task.resume()
}
}
}
/// Convenience method to load data using an URL, creates and resumes an URLSessionDataTask internally.
@ -29,6 +44,10 @@ public extension Backport where Original: URLSession {
@available(tvOS, deprecated: 15.0, message: "No need for .backport any more")
@available(watchOS, deprecated: 8.0, message: "No need for .backport any more")
func data(from url: URL, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) {
if #available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) {
return try await original.data(from: url, delegate: delegate)
} else {
return try await data(for: URLRequest(url: url), delegate: delegate)
}
}
}