I’m having some trouble integrating my Realm-based iOS app with Device Sync. I’ve confirmed that I’m writing to the synced realm successfully as I can see the results on the Mongo DB dashboard, but my subscriptions don’t seem to be working. cycles is always empty, even immediately after adding a cycle to the realm. Not sure if my schema or something else on the backend could be a problem but any help would be greatly appreciated as I’m at my wit’s end.
syncedRealm.subscriptions.count is 2 as expected.
permissions are set such that all users can read and write all data.
import Foundation
import RealmSwift
import Realm
class RealmManager: ObservableObject {
private(set) var syncedRealm: Realm?
@ObservedResults(Cycle.self, sortDescriptor: "startDate") var cycles
@ObservedResults(Day.self, sortDescriptor: "date") var days
let app = App(id: "redacted")
var loggedInUser: User? = nil
init() {
print(Realm.Configuration.defaultConfiguration.fileURL as Any)
Task.init {
try await login()
if let user = loggedInUser {
try await openSyncedRealm(user: user)
}
}
}
@MainActor
func login() async throws {
do{
let user = try await app.login(credentials: Credentials.anonymous)
print("Successfully logged in user: \(user) with id : \(user.id)")
self.loggedInUser = user
} catch {
print("Failed to log in user: \(error)")
}
}
@MainActor
func openSyncedRealm(user: User) async throws {
do {
var config = user.flexibleSyncConfiguration()
config.objectTypes = [Cycle.self, Day.self]
let realm = try await Realm(configuration: config, downloadBeforeOpen: .never)
let subscriptions = realm.subscriptions
try await subscriptions.update {
if let currentSubscription = subscriptions.first(named: "cycles") {
print("Replacing subscription for cycles")
currentSubscription.updateQuery(toType: Cycle.self)
} else {
print("Appending subscription for cycles")
subscriptions.append(QuerySubscription<Cycle>(name: "cycles"))
}
if let currentSubscription = subscriptions.first(named: "days") {
print("Replacing subscription for days")
currentSubscription.updateQuery(toType: Day.self) { day in
day.ownerID == user.id
}
} else {
print("Appending subscription for days")
subscriptions.append(QuerySubscription<Day>(name: "days") { day in
day.ownerID == user.id
})
}
}
self.syncedRealm = realm
print("Successfully opened realm")
} catch {
print("Error opening realm: \(error.localizedDescription)")
}
}