Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 1 addition & 3 deletions CatFact/CatFact/CatFactApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
// CatFactApp.swift
// CatFact
//
// Created by Ian Jiang on 20/12/2024.
//

import SwiftUI

@main
struct CatFactApp: App {
struct CatFactsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
Expand Down
79 changes: 68 additions & 11 deletions CatFact/CatFact/ContentView.swift
Original file line number Diff line number Diff line change
@@ -1,24 +1,81 @@
//
// ContentView.swift
// CatFact
//
// Created by Ian Jiang on 20/12/2024.
// CatFactApp.swift
// ContentView
//

import SwiftUI

struct CatRow {
var image: UIImage?
var fact: String
}

struct ContentView: View {
@State var rows: [CatRow] = []
@State var isLoading = false

var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
ScrollView {
VStack {
ForEach(0..<rows.count, id: \.self) { i in
HStack {
if let img = rows[i].image {
Image(uiImage: img)
.resizable()
.frame(width: 100, height: 100)
} else {
Rectangle().fill(Color.gray).frame(width: 100, height: 100)
}
Text(rows[i].fact)
}
.background(Color.white)
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
rows.remove(at: i)
} label: {
Label("Delete", systemImage: "trash")
}
}
}
}
}
Spacer()
Button("Add Cat Row") {
addCatRow()
}
}
}

func addCatRow() {
isLoading = true
var newRow = CatRow(image: nil, fact: "")
rows.append(newRow)
let idx = rows.count - 1
DispatchQueue.global().async {
if let url = URL(string: "https://cataas.com/cat") {
if let data = try? Data(contentsOf: url), let img = UIImage(data: data) {
DispatchQueue.main.async {
rows[idx].image = img
}
}
}
}
DispatchQueue.global().async {
if let url = URL(string: "https://catfact.ninja/fact") {
if let data = try? Data(contentsOf: url), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let fact = json["fact"] as? String {
DispatchQueue.main.async {
rows[idx].fact = fact
isLoading = false
}
}
}
}
.padding()
}
}

#Preview {
ContentView()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}