Tip
This page contains information about how to add Device Sync to an app. If you are looking for information about what Device Sync is and how it works, see: App Services: Sync Data.
Requisitos previos
Antes de poder acceder a un reino sincronizado desde el cliente, debe Habilite la sincronización en la interfaz de usuario de Atlas App Services. Durante este proceso, debe definir campos consultables que coincidan con los campos de su esquema. También debe definir permisos de lectura y escritura para los usuarios de la aplicación.
En este ejemplo, nuestro modelo incluye un ownerId campo que se asigna al user.id del usuario de Flexible Sync.
class Todo: Object { (primaryKey: true) var _id: ObjectId var name: String = "" var ownerId: String var status: String = "" convenience init(name: String, ownerId: String) { self.init() self.name = name self.ownerId = ownerId } }
Agregue Device Sync a una aplicación de cliente
Connect to the App Services backend
Pass the App ID for your App, which you can find in the App Services UI.
let app = App(id: FLEX_SYNC_APP_ID) // Replace FLEX_SYNC_APP_ID with your Atlas App ID
Autenticar a un usuario
Autentique un usuario en su proyecto de cliente. Aquí, usaremos autenticación anónima.
func login() async throws -> User { // Authenticate with the instance of the app that points // to your backend. Here, we're using anonymous login. let user = try await app.login(credentials: Credentials.anonymous) print("Successfully logged in user: \(user)") return user }
Open a Synced Realm
Abra el dominio como un dominio sincronizado. Puede especificar si un dominio sincronizado debe descargar datos antes de abrirse. Aquí, usamos una configuración de sincronización flexible y especificamos que el SDK siempre debe descargar las actualizaciones más recientes antes de abrir el dominio.Arrancamos el dominio con una suscripción inicial. También especificamos los tipos de objeto que queremos incluir en este dominio.
Tip
If your app accesses Realm in an async/await context, mark the code with @MainActor to avoid threading-related crashes.
func openSyncedRealm(user: User) async { do { var config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in subs.append( QuerySubscription<Todo> { $0.ownerId == user.id }) }) // Pass object types to the Flexible Sync configuration // as a temporary workaround for not being able to add a // complete schema for a Flexible Sync app. config.objectTypes = [Todo.self] let realm = try await Realm(configuration: config, downloadBeforeOpen: .always) useRealm(realm, user) } catch { print("Error opening realm: \(error.localizedDescription)") } }
Use the Realm
La sintaxis para leer, escribir y observar cambios en un dominio sincronizado es idéntica a la de los dominios no sincronizados. Mientras trabaja con datos locales, un subproceso en segundo plano integra, carga y descarga conjuntos de cambios de forma eficiente.
El siguiente código crea un nuevo objeto Task y lo escribe en el realm:
func useRealm(_ realm: Realm, _ user: User) { // Add some tasks let todo = Todo(name: "Do laundry", ownerId: user.id) try! realm.write { realm.add(todo) } }
Importante
Al usar la sincronización, evite escribir en el hilo principal
The fact that Realm performs sync integrations on a background thread means that if you write to your realm on the main thread, there's a small chance your UI could appear to hang as it waits for the background sync thread to finish a write transaction. Therefore, it's a best practice not to write on the main thread when using Device Sync.
Every write transaction for a subscription set has a performance cost. If you need to make multiple updates to a Realm object during a session, consider keeping edited objects in memory until all changes are complete. This improves sync performance by only writing the complete and updated object to your realm instead of every change.