Skip to content

Instantly share code, notes, and snippets.

@saamerm
Created December 9, 2021 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saamerm/64479df10349955e3544cd3936d01b59 to your computer and use it in GitHub Desktop.
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
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