Skip to content

Instantly share code, notes, and snippets.

@alfianlosari
Created May 31, 2021 07:45
Show Gist options
  • Save alfianlosari/847c04cc9502e314e184a74fd495c4ff to your computer and use it in GitHub Desktop.
Save alfianlosari/847c04cc9502e314e184a74fd495c4ff to your computer and use it in GitHub Desktop.
Async URLSession
import Foundation
extension URLSession {
// 1
func data(with url: URL) async throws -> Data {
// 2
try await withCheckedThrowingContinuation { continuation in
// 3
dataTask(with: url) { data, _, error in
// 4
if let error = error {
continuation.resume(throwing: error)
} else if let data = data {
continuation.resume(returning: data)
} else {
continuation.resume(throwing: NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Bad Response"]))
}
}
.resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment