Navigation

Sync Data

Prerequisites

Before you can access a synced realm from the client, you must:

Open a Synced Realm

To open a synced realm for a given partition value, initialize a Realm with a configuration object generated by passing the partition value to the authenticated user’s configuration method:

realm = try! Realm(configuration: user.configuration(partitionValue: partitionValue))

If it is the first time opening that particular realm, especially if it is a read-only realm, use the Realm.asyncOpen() method instead.

Why Use asyncOpen?

The Realm() initializer is convenient, but upon first open of a given realm, it writes the schema to disk. The Realm server interprets this initial local schema as a write. If the realm is read-only, then the operation fails, causing the client to error out. Therefore, it is always recommended to use the Realm.asyncOpen() method the first time you open any given read-only realm.

let user = app.currentUser()
let partitionValue = "myPartition"
Realm.asyncOpen(configuration: user.configuration(partitionValue: partitionValue),
    callback: { (maybeRealm, error) in
        guard error == nil else {
            fatalError("Failed to open realm: \(error!)")
        }
        guard let realm = maybeRealm else {
            fatalError("realm is nil!")
        }
        // realm opened
    })

The partition value specifies which subset of your data to sync. This is typically a user ID, project ID, store ID, or some other category identifier in your app that has particular relevance to the current user.

Sync Data

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.

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 never to write on the main thread when using Realm Sync.

The following code reads a collection of Task objects, watches that collection for changes, then writes a new Task to the realm:

// Read all tasks in the realm. No special syntax required for synced realms.
let tasks = realm.objects(Task.self)

// Watch for changes. No special syntax required for synced realms.
// Retain notificationToken as long as you want to observe.
let notificationToken = tasks.observe { (changes) in
     print("Changed: \(changes)")
}

// Write to the realm. No special syntax required for synced realms.
try! realm.write {
  realm.add(Task(partition: partitionValue, name: "My task"))
}

// Later, when done observing
notificationToken.invalidate()

See also

Threading

Summary

  • Open a synced realm with the configuration object generated when you pass a partition value to the user object’s configuration method.
  • Compared to using a non-synced realm, there is no special syntax for reading from, writing to, or watching objects on a synced realm.
  • You should avoid writing to a synced realm on the main thread.