Created
December 1, 2021 10:38
-
-
Save saamerm/51094dda49465cf63d845b1ad795df87 to your computer and use it in GitHub Desktop.
Simplest way to make an API call in Swift
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 | |
private actor JokeServiceStore { | |
func load() async throws -> String { | |
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) | |
return decodedResponse?.value ?? "" | |
} | |
} | |
class JokeService: ObservableObject { | |
@Published private(set) var joke = "Joke appears here" | |
private let store = JokeServiceStore() | |
public init() { } | |
} | |
extension JokeService { | |
@MainActor | |
func fetchJoke() async throws { | |
joke = try await store.load() | |
} | |
} | |
struct Joke: Codable { | |
let value: String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment