forked from pointfreeco/sqlite-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUIKitDemo.swift
More file actions
146 lines (130 loc) · 3.95 KB
/
UIKitDemo.swift
File metadata and controls
146 lines (130 loc) · 3.95 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import SQLiteData
import SwiftNavigation
import SwiftUI
import UIKit
import UIKitNavigation
final class UIKitCaseStudyViewController: UICollectionViewController, UIKitCaseStudy {
let caseStudyTitle = "UIKit"
let readMe = """
This case study demonstrates how to use the `@FetchAll` tool in a UIKit app. The view \
controller observes changes to the database and updates a collection view when data is added \
or removed.
"""
private var dataSource: UICollectionViewDiffableDataSource<Section, Fact>!
@FetchAll(Fact.order { $0.id.desc() }, animation: .default)
private var facts
private var viewDidLoadTask: Task<Void, Error>?
@Dependency(\.defaultDatabase) var database
init() {
var configuration = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
configuration.trailingSwipeActionsConfigurationProvider = {
[database = _database, facts = _facts] indexPath in
UISwipeActionsConfiguration(
actions: [
UIContextualAction(
style: .destructive,
title: "Delete"
) { action, view, completion in
withErrorReporting {
try database.wrappedValue.write { db in
try Fact.delete(facts.wrappedValue[indexPath.row]).execute(db)
}
}
}
]
)
}
super.init(
collectionViewLayout: UICollectionViewCompositionalLayout.list(
using: configuration
)
)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
viewDidLoadTask?.cancel()
}
override func viewDidLoad() {
super.viewDidLoad()
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Fact> {
cell, indexPath, fact in
var configuration = cell.defaultContentConfiguration()
defer { cell.contentConfiguration = configuration }
configuration.text = fact.body
}
self.dataSource = UICollectionViewDiffableDataSource<Section, Fact>(
collectionView: self.collectionView
) { collectionView, indexPath, item in
collectionView.dequeueConfiguredReusableCell(
using: cellRegistration,
for: indexPath,
item: item
)
}
observe { [weak self] in
guard let self else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Fact>()
snapshot.appendSections([.facts])
snapshot.appendItems(facts, toSection: .facts)
dataSource.apply(snapshot, animatingDifferences: true)
}
viewDidLoadTask = Task { [weak self] in
guard let self else { return }
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
)
if let fact {
await withErrorReporting {
try await database.write { db in
try Fact.insert {
Fact.Draft(body: fact)
}
.execute(db)
}
}
}
}
}
}
nonisolated enum Section: Hashable {
case facts
}
}
@Table
nonisolated private struct Fact: Hashable, Identifiable {
let id: Int
var body: String
}
extension DatabaseWriter where Self == DatabaseQueue {
static var uiKitDemoDatabase: 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 = .uiKitDemoDatabase
}
UINavigationController(caseStudy: UIKitCaseStudyViewController())
}