-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathSwiftUIFlexSyncExampleApp.swift
469 lines (427 loc) · 17.1 KB
/
SwiftUIFlexSyncExampleApp.swift
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
let YOUR_APP_SERVICES_APP_ID_HERE = "swiftuiflexsyncexample-dtgeq"
// :snippet-start: complete-swiftui-flex-sync-quickstart
// :snippet-start: imports
import RealmSwift
import SwiftUI
// :snippet-end:
// :state-start: sync
// :snippet-start: mongodb-realm
// MARK: Atlas App Services (Optional)
// The App Services App. Change YOUR_APP_SERVICES_APP_ID_HERE to your App Services App ID.
// If you don't have a App Services App and don't wish to use Sync for now,
// you can change this to:
// let app: RealmSwift.App? = nil
let app: RealmSwift.App? = RealmSwift.App(id: YOUR_APP_SERVICES_APP_ID_HERE)
// :snippet-end:
// :state-end:
// MARK: Models
// :snippet-start: flexible-sync-models
/// Random adjectives for more interesting demo item names
let randomAdjectives = [
"fluffy", "classy", "bumpy", "bizarre", "wiggly", "quick", "sudden",
"acoustic", "smiling", "dispensable", "foreign", "shaky", "purple", "keen",
"aberrant", "disastrous", "vague", "squealing", "ad hoc", "sweet"
]
/// Random noun for more interesting demo item names
let randomNouns = [
"floor", "monitor", "hair tie", "puddle", "hair brush", "bread",
"cinder block", "glass", "ring", "twister", "coasters", "fridge",
"toe ring", "bracelet", "cabinet", "nail file", "plate", "lace",
"cork", "mouse pad"
]
/// An individual item. Part of an `ItemGroup`.
final class Item: Object, ObjectKeyIdentifiable {
/// The unique ID of the Item. `primaryKey: true` declares the
/// _id member as the primary key to the realm.
@Persisted(primaryKey: true) var _id: ObjectId
/// The name of the Item, By default, a random name is generated.
@Persisted var name = "\(randomAdjectives.randomElement()!) \(randomNouns.randomElement()!)"
/// A flag indicating whether the user "favorited" the item.
@Persisted var isFavorite = false
/// Users can enter a description, which is an empty string by default
@Persisted var itemDescription = ""
/// The backlink to the `ItemGroup` this item is a part of.
@Persisted(originProperty: "items") var group: LinkingObjects<ItemGroup>
// :state-start: sync
/// Store the user.id as the ownerId so you can query for the user's objects with Flexible Sync
/// Add this to both the `ItemGroup` and the `Item` objects so you can read and write the linked objects.
@Persisted var ownerId = ""
// :state-end:
}
/// Represents a collection of items.
final class ItemGroup: Object, ObjectKeyIdentifiable {
/// The unique ID of the ItemGroup. `primaryKey: true` declares the
/// _id member as the primary key to the realm.
@Persisted(primaryKey: true) var _id: ObjectId
/// The collection of Items in this group.
@Persisted var items = RealmSwift.List<Item>()
// :state-start: sync
/// Store the user.id as the ownerId so you can query for the user's objects with Flexible Sync
/// Add this to both the `ItemGroup` and the `Item` objects so you can read and write the linked objects.
@Persisted var ownerId = ""
// :state-end:
}
// :snippet-end:
// :snippet-start: preview-extend-model-class-with-objects
extension Item {
static let item1 = Item(value: ["name": "fluffy coasters", "isFavorite": false, "ownerId": "previewRealm"])
static let item2 = Item(value: ["name": "sudden cinder block", "isFavorite": true, "ownerId": "previewRealm"])
static let item3 = Item(value: ["name": "classy mouse pad", "isFavorite": false, "ownerId": "previewRealm"])
}
// :snippet-end:
// :snippet-start: preview-extend-model-class-with-realm
extension ItemGroup {
static let itemGroup = ItemGroup(value: ["ownerId": "previewRealm"])
static var previewRealm: Realm {
var realm: Realm
let identifier = "previewRealm"
let config = Realm.Configuration(inMemoryIdentifier: identifier)
do {
realm = try Realm(configuration: config)
// Check to see whether the in-memory realm already contains an ItemGroup.
// If it does, we'll just return the existing realm.
// If it doesn't, we'll add an ItemGroup and append the Items.
let realmObjects = realm.objects(ItemGroup.self)
if realmObjects.count == 1 {
return realm
} else {
try realm.write {
realm.add(itemGroup)
itemGroup.items.append(objectsIn: [Item.item1, Item.item2, Item.item3])
}
return realm
}
} catch let error {
fatalError("Can't bootstrap item data: \(error.localizedDescription)")
}
}
}
// :snippet-end:
// MARK: Views
// MARK: Main Views
// :snippet-start: content-view
/// The main screen that determines whether to present the SyncContentView or the LocalOnlyContentView.
// :state-start: local
/// For now, it always displays the LocalOnlyContentView.
// :state-end:
@main
struct ContentView: SwiftUI.App {
var body: some Scene {
WindowGroup {
// :state-start: sync
// Using Sync?
if let app = app {
SyncContentView(app: app)
} else {
LocalOnlyContentView()
}
// :state-end:
// :state-uncomment-start: local
// LocalOnlyContentView()
// :state-uncomment-end:
}
}
}
// :snippet-end:
// :snippet-start: local-only-content-view
/// The main content view if not using Sync.
struct LocalOnlyContentView: View {
@State var searchFilter: String = ""
// :snippet-start: implicitly-open-realm
// Implicitly use the default realm's objects(ItemGroup.self)
@ObservedResults(ItemGroup.self) var itemGroups
// :snippet-end:
var body: some View {
if let itemGroup = itemGroups.first {
// Pass the ItemGroup objects to a view further
// down the hierarchy
ItemsView(itemGroup: itemGroup)
} else {
// For this small app, we only want one itemGroup in the realm.
// You can expand this app to support multiple itemGroups.
// For now, if there is no itemGroup, add one here.
ProgressView().onAppear {
$itemGroups.append(ItemGroup())
}
}
}
}
// :snippet-end:
// :state-start: sync
// :snippet-start: flex-sync-content-view
/// This view observes the Realm app object.
/// Either direct the user to login, or open a realm
/// with a logged-in user.
struct SyncContentView: View {
// Observe the Realm app object in order to react to login state changes.
@ObservedObject var app: RealmSwift.App
var body: some View {
if let user = app.currentUser {
// :snippet-start: flex-sync-config-initial-subscriptions
// Create a `flexibleSyncConfiguration` with `initialSubscriptions`.
// We'll inject this configuration as an environment value to use when opening the realm
// in the next view, and the realm will open with these initial subscriptions.
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
// Check whether the subscription already exists. Adding it more
// than once causes an error.
if let foundSubscriptions = subs.first(named: "user_groups") {
// Existing subscription found - do nothing
return
} else {
// Add queries for any objects you want to use in the app
// Linked objects do not automatically get queried, so you
// must explicitly query for all linked objects you want to include
subs.append(QuerySubscription<ItemGroup>(name: "user_groups") {
// Query for objects where the ownerId is equal to the app's current user's id
// This means the app's current user can read and write their own data
$0.ownerId == user.id
})
subs.append(QuerySubscription<Item>(name: "user_items") {
$0.ownerId == user.id
})
}
})
// :snippet-end:
// :snippet-start: realm-config-environment-object
OpenSyncedRealmView()
.environment(\.realmConfiguration, config)
// :snippet-end:
} else {
// If there is no user logged in, show the login view.
LoginView()
}
}
}
// :snippet-end:
// :snippet-start: open-realm-view-flex-sync
/// This view opens a synced realm.
struct OpenSyncedRealmView: View {
// :snippet-start: flex-sync-property-wrapper
// We've injected a `flexibleSyncConfiguration` as an environment value,
// so `@AsyncOpen` here opens a realm using that configuration.
// :snippet-start: fs-property-wrapper-sans-config-comment
@AsyncOpen(appId: YOUR_APP_SERVICES_APP_ID_HERE, timeout: 4000) var asyncOpen
// :snippet-end:
// :snippet-end:
var body: some View {
// Because we are setting the `ownerId` to the `user.id`, we need
// access to the app's current user in this view.
let user = app?.currentUser
switch asyncOpen {
// Starting the Realm.asyncOpen process.
// Show a progress view.
case .connecting:
ProgressView()
// Waiting for a user to be logged in before executing
// Realm.asyncOpen.
case .waitingForUser:
ProgressView("Waiting for user to log in...")
// The realm has been opened and is ready for use.
// Show the content view.
case .open(let realm):
// :snippet-start: add-ownerid-to-group
ItemsView(itemGroup: {
if realm.objects(ItemGroup.self).count == 0 {
try! realm.write {
// Because we're using `ownerId` as the queryable field, we must
// set the `ownerId` to equal the `user.id` when creating the object
realm.add(ItemGroup(value: ["ownerId":user!.id]))
}
}
return realm.objects(ItemGroup.self).first!
}(), leadingBarButton: AnyView(LogoutButton())).environment(\.realm, realm)
// :snippet-end:
// The realm is currently being downloaded from the server.
// Show a progress view.
case .progress(let progress):
ProgressView(progress)
// Opening the Realm failed.
// Show an error view.
case .error(let error):
ErrorView(error: error)
}
}
}
// :snippet-end:
struct ErrorView: View {
var error: Error
var body: some View {
VStack {
Text("Error opening the realm: \(error.localizedDescription)")
}
}
}
// MARK: Authentication Views
// :snippet-start: login-view
/// Represents the login screen. We will have a button to log in anonymously.
struct LoginView: View {
// Hold an error if one occurs so we can display it.
@State var error: Error?
// Keep track of whether login is in progress.
@State var isLoggingIn = false
var body: some View {
VStack {
if isLoggingIn {
ProgressView()
}
if let error = error {
Text("Error: \(error.localizedDescription)")
}
Button("Log in anonymously") {
// Button pressed, so log in
isLoggingIn = true
Task {
do {
let user = try await app!.login(credentials: .anonymous)
// Other views are observing the app and will detect
// that the currentUser has changed. Nothing more to do here.
print("Logged in as user with id: \(user.id)")
} catch {
print("Failed to log in: \(error.localizedDescription)")
// Set error to observed property so it can be displayed
self.error = error
return
}
}
}.disabled(isLoggingIn)
}
}
}
// :snippet-end:
// :snippet-start: preview-view-associated-with-sync
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}
// :snippet-end:
// :snippet-start: logout-button
/// A button that handles logout requests.
struct LogoutButton: View {
@State var isLoggingOut = false
var body: some View {
Button("Log Out") {
guard let user = app!.currentUser else {
return
}
isLoggingOut = true
Task {
do {
try await app!.currentUser!.logOut()
// Other views are observing the app and will detect
// that the currentUser has changed. Nothing more to do here.
} catch {
print("Error logging out: \(error.localizedDescription)")
}
}
}.disabled(app!.currentUser == nil || isLoggingOut)
}
}
// :snippet-end:
// :state-end:
// MARK: Item Views
// :snippet-start: items-view
/// The screen containing a list of items in an ItemGroup. Implements functionality for adding, rearranging,
/// and deleting items in the ItemGroup.
struct ItemsView: View {
@ObservedRealmObject var itemGroup: ItemGroup
/// The button to be displayed on the top left.
var leadingBarButton: AnyView?
var body: some View {
// :state-start: sync
let user = app?.currentUser
// :state-end:
NavigationView {
VStack {
// The list shows the items in the realm.
List {
ForEach(itemGroup.items) { item in
ItemRow(item: item)
}.onDelete(perform: $itemGroup.items.remove)
.onMove(perform: $itemGroup.items.move)
}
.listStyle(GroupedListStyle())
.navigationBarTitle("Items", displayMode: .large)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading: self.leadingBarButton,
// Edit button on the right to enable rearranging items
trailing: EditButton())
// :snippet-start: add-ownerid-to-create-button-code
// Action bar at bottom contains Add button.
HStack {
Spacer()
Button(action: {
// The bound collection automatically
// handles write transactions, so we can
// append directly to it.
// :state-start: sync
// Because we are using Flexible Sync, we must set
// the item's ownerId to the current user.id when we create it.
$itemGroup.items.append(Item(value: ["ownerId":user!.id]))
// :state-end:
// :state-uncomment-start: local
// $itemGroup.items.append(Item())
// :state-uncomment-end:
}) { Image(systemName: "plus") }
}.padding()
// :snippet-end:
}
}
}
}
// :snippet-end:
// :snippet-start: preview-with-realm
struct ItemsView_Previews: PreviewProvider {
static var previews: some View {
let realm = ItemGroup.previewRealm
let itemGroup = realm.objects(ItemGroup.self)
ItemsView(itemGroup: itemGroup.first!)
}
}
// :snippet-end:
// :snippet-start: item-row-and-details
/// Represents an Item in a list.
struct ItemRow: View {
@ObservedRealmObject var item: Item
var body: some View {
// You can click an item in the list to navigate to an edit details screen.
NavigationLink(destination: ItemDetailsView(item: item)) {
Text(item.name)
if item.isFavorite {
// If the user "favorited" the item, display a heart icon
Image(systemName: "heart.fill")
}
}
}
}
// :snippet-start: item-details-view
/// Represents a screen where you can edit the item's name.
// :snippet-start: quick-write-observed-realm-object
struct ItemDetailsView: View {
@ObservedRealmObject var item: Item
var body: some View {
VStack(alignment: .leading) {
Text("Enter a new name:")
// Accept a new name
TextField("New name", text: $item.name)
.navigationBarTitle(item.name)
.navigationBarItems(trailing: Toggle(isOn: $item.isFavorite) {
Image(systemName: item.isFavorite ? "heart.fill" : "heart")
})
}.padding()
}
}
// :snippet-end:
// :snippet-end:
// :snippet-end:
// :snippet-start: preview-detail-view
struct ItemDetailsView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ItemDetailsView(item: Item.item2)
}
}
}
// :snippet-end:
// :snippet-end: