Last active
December 4, 2023 02:04
-
-
Save benigumocom/98231e1d115971f0b7bcf4417f63b822 to your computer and use it in GitHub Desktop.
【Swift】Playground で API から JSON データを取得して デコード して画像を表示する 🐶 👉 https://android.benigumo.com/20231204/playground-api/
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 WebKit | |
import PlaygroundSupport | |
struct Dog: Decodable { | |
let message: String | |
let status: String | |
} | |
enum DogError: Error { | |
case missingData | |
case wrongDataFormat(error: Error) | |
} | |
func get(url: String) async throws -> Data { | |
let session = URLSession.shared | |
guard let (data, response) = try? await session.data(from: URL(string: url)!), | |
let httpResponse = response as? HTTPURLResponse, | |
httpResponse.statusCode == 200 | |
else { | |
throw DogError.missingData | |
} | |
return data | |
} | |
func decode<T: Decodable>(data: Data) throws -> T { | |
do { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .millisecondsSince1970 | |
return try decoder.decode(T.self, from: data) | |
} catch { | |
throw DogError.wrongDataFormat(error: error) | |
} | |
} | |
func show(url: String) { | |
let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) | |
let request = URLRequest(url: URL(string: url)!) | |
view.load(request) | |
PlaygroundPage.current.liveView = view | |
} | |
Task { @MainActor in | |
let url = "https://dog.ceo/api/breeds/image/random" | |
let data = try await get(url: url) | |
let dog = try decode(data: data) as Dog | |
show(url: dog.message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment