Skip to content

Commit

Permalink
a
Browse files Browse the repository at this point in the history
  • Loading branch information
swhitty committed Oct 30, 2024
1 parent 0482ba5 commit a1bb9a2
Showing 1 changed file with 40 additions and 38 deletions.
78 changes: 40 additions & 38 deletions FlyingFox/Sources/URLSession+Async.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,41 +32,43 @@
import Foundation
import FlyingSocks

#if canImport(FoundationNetworking)
import FoundationNetworking

extension URLSession {

// Ports macOS Foundation method to Linux
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
let state = Mutex((isCancelled: false, task: URLSessionDataTask?.none))
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
let task = dataTask(with: request) { data, response, error in
guard let data = data, let response = response else {
continuation.resume(throwing: error!)
return
}
continuation.resume(returning: (data, response))
}
let shouldCancel = state.withLock {
$0.task = task
return $0.isCancelled
}
task.resume()
if shouldCancel {
task.cancel()
}
}
} onCancel: {
let taskToCancel = state.withLock {
$0.isCancelled = true
return $0.task
}
if let taskToCancel {
taskToCancel.cancel()
}
}
}
}
#endif
//#if canImport(FoundationNetworking)
//import FoundationNetworking
//
//extension URLSession {
//
// // Ports macOS Foundation method to Linux
// func data(for request: URLRequest) async throws -> (Data, URLResponse) {
//
//
// let state = Mutex((isCancelled: false, task: URLSessionDataTask?.none))
// return try await withTaskCancellationHandler {
// try await withCheckedThrowingContinuation { continuation in
// let task = dataTask(with: request) { data, response, error in
// guard let data = data, let response = response else {
// continuation.resume(throwing: error!)
// return
// }
// continuation.resume(returning: (data, response))
// }
// let shouldCancel = state.withLock {
// $0.task = task
// return $0.isCancelled
// }
// task.resume()
// if shouldCancel {
// task.cancel()
// }
// }
// } onCancel: {
// let taskToCancel = state.withLock {
// $0.isCancelled = true
// return $0.task
// }
// if let taskToCancel {
// taskToCancel.cancel()
// }
// }
// }
//}
//#endif

0 comments on commit a1bb9a2

Please sign in to comment.