El Swift SDK proporciona envoltorios de propiedades para abrir un reino de una manera compatible con SwiftUI.
Puede:
Abrir implícitamente un reino con un
defaultConfigurationo especifique una configuración diferente. Esto funciona tanto para dominios sincronizados como no sincronizados.Descargue siempre los cambios antes de abrir un realm sincronizado, que se agota cuando el usuario está desconectado.
Open a synced realm even when a user is offline. The realm may lack the most recent data.
Abre un Realm con una configuración
When you use @ObservedRealmObject or @ObservedResults, these property wrappers implicitly open a realm and retrieve the specified objects or results.
// Implicitly use the default realm's objects(Dog.self) (Dog.self) var dogs
Nota
The @ObservedResults property wrapper is intended for use in a SwiftUI View. If you want to observe results in a view model, register a change listener.
Cuando no se especifica una configuración, estos contenedores de propiedades usan la defaultConfiguration. Puedes establecer la defaultConfiguration globalmente, y los contenedores de propiedades en toda la aplicación usarán esa configuración cuando abran implícitamente un realm.
You can provide alternative configurations that the property wrappers use to implicitly open the realm. You might want to do this when using multiple configurations in your app, as in cases where you have both a SyncConfiguration and a local Configuration. To do this, create explicit configurations. Then, use environment injection to pass the respective configurations to the views that need them. Passing a configuration to a view where property wrappers open a realm uses the passed configuration instead of the defaultConfiguration.
Open a Synced Realm
New in version 10.12.0.
These SwiftUI property wrappers open synced realms and populate views. The main difference between these property wrappers is whether the user must be online:
Para descargar actualizaciones de tu aplicación Atlas App Services antes de abrir un realm, utiliza el contenedor de propiedad @AsyncOpen. Esto requiere que el usuario tenga una conexión a la red.
To open a synced realm regardless of whether the user has a network connection, use the @AutoOpen property wrapper. This property wrapper enables developers to design offline-first capabilities into their apps.
Tip
Migrar a la sincronización flexible
You can automatically migrate your App Services Device Sync Mode from Partition-Based Sync to Flexible Sync. This enables you to take advantage of the more expressive and granular Flexible Sync subscriptions and permissions to manage what synced data your users can read and write. For more information, refer to Migrate from Partition-Based Sync to Flexible Sync.
Download Changes Before Opening a Synced Realm
Use the @AsyncOpen property wrapper for apps that require up-to-date information from the server, such as game apps with live leaderboards that the user can play on multiple devices. This ensures the user is never using the app with stale data.
Nuevo en la versión 10.27.0.
Realm Swift SDK version 10.27.0 adds Flexible Sync versions of the property wrappers to open Realm with SwiftUI. You can add subscription queries in .onAppear after opening the realm.
(appId: flexibleSyncAppId, timeout: 4000) var asyncOpen
New in version 10.28.0.
You can create a flexibleSyncConfiguration() with the initialSubscriptions parameter. You can use this parameter to subscribe to Flexible Sync queries in the configuration. If this runs more than once - for example, if it's in a view that reloads regularly - check whether the subscription exists already before adding it. Adding the same subscription again throws an error.
// 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 let peopleSubscriptionExists = subs.first(named: "people") let dogSubscriptionExists = subs.first(named: "dogs") // Check whether the subscription already exists. Adding it more // than once causes an error. if (peopleSubscriptionExists != nil) && (dogSubscriptionExists != nil) { // Existing subscriptions 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<Person>(name: "people")) subs.append(QuerySubscription<Dog>(name: "dogs")) } })
Luego, pase la configuración a la vista que contiene los contenedores de propiedades como un objeto de entorno.
OpenFlexibleSyncRealmView() .environment(\.realmConfiguration, config)
For a complete example, see the SwiftUI Quick Start.
To open a realm with Partition-Based Sync, add a partitionValue to the property wrapper:
(appId: YOUR_APP_SERVICES_APP_ID_HERE, partitionValue: "", timeout: 4000) var asyncOpen
This SwiftUI property wrapper initiates Realm.asyncOpen() for the current user. The property wrapper publishes states, represented by the AsyncOpenState enum, which you can use to update the view.
Ejemplo
This example illustrates one way you might use @AsyncOpen to open a realm in a view. First, check for a user, or log them in. Then, attempt to open the realm, switching on the AsyncOpenState to display an appropriate view. When the realm opens successfully, inject it as an environment value to populate the view.
/// This view opens a synced realm. struct OpenFlexibleSyncRealmView: View { // We've injected a `flexibleSyncConfiguration` as an environment value, // so `@AsyncOpen` here opens a realm using that configuration. (appId: flexibleSyncAppId, timeout: 4000) var asyncOpen var body: some View { 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): // Do something with the realm UseRealmView(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): ErrorView(error: error) } } }
/// This view opens a synced realm. struct OpenPartitionBasedSyncRealm: View { // @AsyncOpen attempts to connect to the server and download remote changes // before the realm opens. If there is no network connection, // AsyncOpen cannot load changes and the realm does not open. // We can use an empty string as the partitionValue here because we're // injecting the user.id as an environment value from the LoginView. (appId: YOUR_APP_SERVICES_APP_ID_HERE, partitionValue: "", timeout: 4000) var asyncOpen var body: some View { 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): // Do something with the realm UseRealmView(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): ErrorView(error: error) } } }
Open a Synced Realm Offline
Al igual que @AsyncOpen, @AutoOpen intenta descargar actualizaciones antes de abrir el realm. Sin embargo, si no hay una conexión de red disponible, este método abre en su lugar un realm con datos en el dispositivo.
Use this property wrapper for apps where it's not a problem for the user to work with potentially stale data, such as note-taking apps where users should be able to work with data on the device
(appId: "app_id") var autoOpen
(appId: "app_id", partitionValue: <partition_value>) var autoOpen
Este propiedad contenedor de SwiftUI intenta descargar actualizaciones antes de abrir un realm para el usuario actual. Si no hay conexión a Internet, este contenedor de propiedades retorna la versión más actualizada del archivo Realm local para el appId correspondiente y la configuración Flexible Sync o Partition-Based Sync.
The property wrapper publishes states, represented by the AsyncOpenState enum, which you can use to update the view. For a full example, see the @AsyncOpen code examples above.