6

the new realm mobile platform is advertised with offline support, however most tutorials does not show how that works in the examples...

for example, in their todo app example this is the code used to connect to the server database

SyncUser.logIn(with: .usernamePassword(username: username, password: password, register: false), server: URL(string: "http://127.0.0.1:9080")!) { user, error in
guard let user = user else {
    fatalError(String(describing: error))
}

DispatchQueue.main.async {
    // Open Realm
    let configuration = Realm.Configuration(
        syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://127.0.0.1:9080/~/realmtasks")!)
    )
    self.realm = try! Realm(configuration: configuration)

    // Show initial tasks
    func updateList() {
        if self.items.realm == nil, let list = self.realm.objects(TaskList.self).first {
            self.items = list.items
        }
        self.tableView.reloadData()
    }
    updateList()

    // Notify us when Realm changes
    self.notificationToken = self.realm.addNotificationBlock { _ in
        updateList()
    }
}
}

when the user goes offline, the returned user variable is nil, and you cant use the configured realm on the server, but the code doesn't show how to get the synced data from the mirrored local database... do you have to manually copy the items from the online database to a manually created local database everytime the user goes online?

Hadi
  • 705
  • 8
  • 23

1 Answers1

6

After you successfully log in (or register) the user it's cached in the device's keychain and you can retrieve it via currentUser property or alternatively if your app supports multiple users all even when you're offline.

Please note if you call logout on a user then it will be removed from the keychain and you will have to be online and log in again.

Dmitry
  • 7,300
  • 6
  • 32
  • 55
  • do you know of a good way to do this without ever actually establishing connection/logging in the first time? For instance, if you are guaranteed that the app is up to date and there are no schema changes? One way is to create a local realm and then copy all of the data over once you have established sync, but this seems difficult and sort of defeats the purpose of using realm for offline in the first place. – Brooks DuBois Jun 19 '19 at 20:18