Skip to content

Instantly share code, notes, and snippets.

@saamerm
Created December 1, 2021 10:38
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/51094dda49465cf63d845b1ad795df87 to your computer and use it in GitHub Desktop.
Save saamerm/51094dda49465cf63d845b1ad795df87 to your computer and use it in GitHub Desktop.
Simplest way to make an API call in Swift
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