Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Sync Data

Transmitir datos a Atlas - Swift SDK

New in version 10.29.0.

Puede usar Ingesta de datos para transmitir datos desde la aplicación cliente a una aplicación Atlas App Services habilitada para Flexible Sync.

You might want to sync data unidirectionally in IoT applications, such as a weather sensor sending data to the cloud. Data Ingest is also useful for writing other types of immutable data where you do not require conflict resolution, such as creating invoices from a retail app or logging application events.

Data Ingest is optimized to provide performance improvements for heavy client-side insert-only workloads.

1

Puede sincronizar datos unidireccionalmente cuando ese objeto es un AsymmetricObject. Defina un AsymmetricObject derivando de AsymmetricObject:

class WeatherSensor: AsymmetricObject {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var deviceId: String
@Persisted var temperatureInFahrenheit: Float
@Persisted var barometricPressureInHg: Float
@Persisted var windSpeedInMph: Int
}

For more information on how to define an AsymmetricObject, see: Define an AsymmetricObject.

2

Para transmitir datos desde el cliente a su aplicación backend, debe conectarse a un backend de App Services y autenticar a un usuario.

let app = App(id: INSERT_APP_ID_HERE)
do {
let user = try await login()
await openSyncedRealm(user: user)
} catch {
print("Error logging in: \(error.localizedDescription)")
}
func login() async throws -> User {
let user = try await app.login(credentials: .anonymous)
return user
}

Data Ingest es una funcionalidad de Flexible Sync, por lo que la aplicación a la que te conectes debe usar Flexible Sync.

3

Una vez que tenga un usuario autenticado, puede abrir un dominio sincronizado mediante flexibleSyncConfiguration(). Especifique los AsymmetricObject tipos que desea sincronizar.

@MainActor
func openSyncedRealm(user: User) async {
do {
var asymmetricConfig = user.flexibleSyncConfiguration()
asymmetricConfig.objectTypes = [WeatherSensor.self]
let asymmetricRealm = try await Realm(configuration: asymmetricConfig)
await useRealm(asymmetricRealm, user)
} catch {
print("Error opening realm: \(error.localizedDescription)")
}
}

Unlike bidirectional Sync, Data Ingest does not use a Flexible Sync subscription.

Nota

Dominios sincronizados y no sincronizados mixtos en proyectos

The AsymmetricObject type is incompatible with non-synced realms. If your project uses both a synced and non-synced realm, you must explicitly pass a subset of classes in your Realm configuration to exclude the AsymmetricObject from your non-synced realm.

Automatic schema discovery means that opening a non-synced realm without specifically excluding the AsymmetricObject from the configuration can throw an error related to trying to use an incompatible object type.

4

Una vez que tenga un reino abierto, puede crear un AsymmetricObject dentro de una transacción de escritura usando create(_ type:, value:).

@MainActor
func useRealm(_ asymmetricRealm: Realm, _ user: User) async {
try! asymmetricRealm.write {
asymmetricRealm.create(WeatherSensor.self,
value: [ "_id": ObjectId.generate(),
"deviceId": "WX1278UIT",
"temperatureInFahrenheit": 66.7,
"barometricPressureInHg": 29.65,
"windSpeedInMph": 2
])
}
}

You cannot read these objects. Once created, they sync to the App Services backend and the linked Atlas database.

Atlas Device Sync gestiona completamente el ciclo de vida de estos datos. Se mantiene en el dispositivo hasta que la sincronización de Data Ingest se completa y luego se elimina del dispositivo.

Volver

Registrar eventos de Realm

En esta página