Last active
December 4, 2022 16:35
-
-
Save gotev/c80813efa1b82c507bddef08d9fe72eb to your computer and use it in GitHub Desktop.
Swift Multiplatform Experiments. Read comments below.
This file contains hidden or 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 | |
// needed for Linux | |
#if canImport(FoundationNetworking) | |
import FoundationNetworking | |
#endif | |
// New async await URLSession extensions are available solely on Apple platform | |
// so this polyfill it's necessary, otherwise the code does not compile on Linux | |
extension URLSession { | |
func universalData(for request: URLRequest) async throws -> (Data, URLResponse?) { | |
#if canImport(FoundationNetworking) | |
print("On Linux") | |
return await withCheckedContinuation { continuation in | |
URLSession.shared.dataTask(with: request) { data, response, _ in | |
guard let data = data else { | |
fatalError() | |
} | |
continuation.resume(returning: (data, response)) | |
}.resume() | |
} | |
#else | |
print("On macOS") | |
return try await URLSession.shared.data(for: request) | |
#endif | |
} | |
} | |
struct Dog: Codable { | |
let message: String | |
let status: String | |
var url: URL { URL(string: message)! } | |
} | |
func fetchDog() async throws -> Dog { | |
let dogURL = URL(string: "https://dog.ceo/api/breeds/image/random")! | |
let request = URLRequest(url: dogURL) | |
let (data, _) = try await URLSession.shared.universalData(for: request) | |
return try JSONDecoder().decode(Dog.self, from: data) | |
} | |
do { | |
print(try await fetchDog()) | |
} catch { | |
print(error) | |
print("ouch") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It runs successfully on:
Useful Article about Swift Concurrency on Linux