A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.mongodb.com/docs/atlas/device-sdks/sdk/swift/sync/add-sync-to-app/ below:

Add Device Sync to an App - Swift SDK - Atlas Device SDKs

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.

Before you can access a synced realm from the client, you must Enable sync in the Atlas App Services UI. During this process, you must define queryable fields that match fields in your schema. You also define read and write permissions for app users.

In this example, our model includes an ownerId field that maps to the user.id of the Flexible Sync user.

class Todo: Object {    @Persisted(primaryKey: true) var _id: ObjectId    @Persisted var name: String = ""    @Persisted var ownerId: String    @Persisted var status: String = ""    convenience init(name: String, ownerId: String) {        self.init()        self.name = name        self.ownerId = ownerId    }}

Authenticate a user in your client project. Here, we'll use anonymous authentication.

func login() async throws -> User {            let user = try await app.login(credentials: Credentials.anonymous)    print("Successfully logged in user: \(user)")    return user}

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.

@MainActorfunc openSyncedRealm(user: User) async {    do {        var config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in            subs.append(                QuerySubscription<Todo> {                    $0.ownerId == user.id                })        })                                config.objectTypes = [Todo.self]        let realm = try await Realm(configuration: config, downloadBeforeOpen: .always)        useRealm(realm, user)    } catch {        print("Error opening realm: \(error.localizedDescription)")    }}

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.

The following code creates a new Task object and writes it to the realm:

@MainActorfunc useRealm(_ realm: Realm, _ user: User) {        let todo = Todo(name: "Do laundry", ownerId: user.id)    try! realm.write {        realm.add(todo)    }}
Important 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.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4