OpenSyncedRealmView
This wiew will check how our connection to MongoDB Atlas progress and will inform us if there's any error. Once is connected with a Synced Realm (in case .open(let realm)
) it shows our old friend MainView
. As we're adding to the environment
this new, synced Realm our app will keep working as before, storing everything locally AND syncing to our MongoDB Database.
import SwiftUI
import RealmSwift
/// This view opens a synced realm.
struct OpenSyncedRealmView: View {
@ObservedObject var app: RealmSwift.App
// We've injected a `flexibleSyncConfiguration` as an environment value,
// so `@AsyncOpen` here opens a realm using that configuration.
@AsyncOpen(appId: nil, timeout: 4000) var asyncOpen
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):
MainView()
.environment(\.realm, realm)
// 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):
Text(error.localizedDescription)
.font(.callout)
.multilineTextAlignment(.center)
.padding(.bottom, 40).padding()
}
}
}