forked from pointfreeco/sqlite-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftUIDemo.swift
More file actions
93 lines (85 loc) · 2.22 KB
/
SwiftUIDemo.swift
File metadata and controls
93 lines (85 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import SQLiteData
import SwiftUI
struct SwiftUIDemo: SwiftUICaseStudy {
let readMe = """
This demonstrates how to use the `@FetchAll` and `@FetchOne` queries directly in a SwiftUI \
view. The tools listen for changes in the database so that when the table changes it \
automatically updates state and re-renders the view.
You can also delete rows by swiping on a row and tapping the "Delete" button.
"""
let caseStudyTitle = "SwiftUI Views"
@FetchAll(Fact.order { $0.id.desc() }, animation: .default)
private var facts
@FetchOne(Fact.count(), animation: .default)
var factsCount = 0
@Dependency(\.defaultDatabase) var database
var body: some View {
List {
Section {
Text("Facts: \(factsCount)")
.font(.largeTitle)
.bold()
.contentTransition(.numericText(value: Double(factsCount)))
}
Section {
ForEach(facts) { fact in
Text(fact.body)
}
}
}
.task {
do {
var number = 0
while true {
try await Task.sleep(for: .seconds(1))
number += 1
let fact = try await String(
decoding: URLSession.shared
.data(from: URL(string: "http://numberapi.com/\(number)")!).0,
as: UTF8.self
)
try await database.write { db in
try Fact.insert {
Fact.Draft(body: fact)
}
.execute(db)
}
}
} catch {}
}
}
}
@Table
nonisolated private struct Fact: Identifiable {
let id: Int
var body: String
}
extension DatabaseWriter where Self == DatabaseQueue {
static var swiftUIDatabase: Self {
let databaseQueue = try! DatabaseQueue()
var migrator = DatabaseMigrator()
migrator.registerMigration("Create 'facts' table") { db in
try #sql(
"""
CREATE TABLE "facts" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"body" TEXT NOT NULL
) STRICT
"""
)
.execute(db)
}
try! migrator.migrate(databaseQueue)
return databaseQueue
}
}
#Preview {
let _ = prepareDependencies {
$0.defaultDatabase = .swiftUIDatabase
}
NavigationStack {
CaseStudyView {
SwiftUIDemo()
}
}
}