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
Open the realm as a synced realm. You can specify whether a synced realm should download data before it opens. Here, we use a Flexible Sync configuration and specify that the SDK should always download the most recent updates before opening the realm. We bootstrap the realm with an initial subscription. We also specify the object types that we want to include in this realm.
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
The syntax to read, write, and watch for changes on a synced realm is identical to the syntax for non-synced realms. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.
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
When Using Sync, Avoid Writes on the Main Thread
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.