Created
May 31, 2021 07:45
-
-
Save alfianlosari/847c04cc9502e314e184a74fd495c4ff to your computer and use it in GitHub Desktop.
Async URLSession
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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