Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show cat fact #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions CatFact/CatFact/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,29 @@
import SwiftUI

struct ContentView: View {
var c = CatFact()

var buttonTitle = "Get Fact"

@State
var list: [CatFact] = []

var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
ScrollView {
VStack {
ForEach(Array(list.enumerated()), id: \.offset) { fact in
Text(fact.element.fact ?? "")

// Text(fact.element.length)
}

Button("Get Fact") {
Task { @MainActor in
try? await c.fetch()
list.append(c)
}
}
}
}
.padding()
}
Expand All @@ -22,3 +39,27 @@ struct ContentView: View {
#Preview {
ContentView()
}


class CatFact: ObservableObject, Codable {
var fact: String?
var length: Int?
var url: String?

init(fact: String? = nil, length: Int? = nil, url: String? = nil) {
self.fact = fact
self.length = length
self.url = url
}

func fetch() async throws {
url = "https://catfact.ninja/fact"
let request = URLRequest(url: URL(string: url!)!)
let response = try await URLSession.shared.data(for: request)

let catFact = try JSONDecoder().decode(CatFact.self, from: response.0)

fact = catFact.fact
length = catFact.length
}
}