Created
December 9, 2021 07:16
-
-
Save saamerm/64479df10349955e3544cd3936d01b59 to your computer and use it in GitHub Desktop.
The simplest way possible to make an async call using SwiftUI, using the ChuckNorris ICNDB API as an example
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 | |
import SwiftUI | |
struct ContentView: View { | |
@State private var joke: String = "" | |
var body: some View { | |
Text(joke) | |
Button { | |
Task { | |
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.chucknorris.io/jokes/random")!) | |
let decodedResponse = try? JSONDecoder().decode(Joke.self, from: data) | |
joke = decodedResponse?.value ?? "" | |
} | |
} label: { | |
Text("Fetch Joke") | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
struct Joke: Codable { | |
let value: String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment