rparikh rparikh - 1 year ago 73
Swift Question

Synced Realm not being loaded on launch

I'm attempting to use Realm Object Server in my ios app. I am hosting it on AWS, and I can successfully read and write to it. However, I'm having a problem accessing the synced realm after launching my app. On launch, I have a login view controller (very similar to the one provided in the example app)

After authenticating successfully, I want to access the synced Realm to decide which view controller to present.

@IBAction func logIn(sender: AnyObject?) {
guard userInputValid() else {
self.logInButton.isHidden = true
SyncUser.authenticate(with: Credential.usernamePassword(username: userNameTextField.text!, password: passwordTextField.text!, actions: []), server: syncAuthURL!, onCompletion: { user, error in
guard let user = user else {
self.presentError(error: error as! NSError)
self.logInButton.isHidden = false

Realm.Configuration.defaultConfiguration = Realm.Configuration(
syncConfiguration: (user, self.syncServerURL!),
objectTypes: [Dot.self, Mod.self]

let realm = try! Realm()
// realm.objects(Dot.self).count == 0 here even though there is a Dot object persisted in the server
// When I access the realm later in the app (e.g in a viewDidAppear of another controller) the object is there
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let vc = DotCollectionViewController(nibName: "DotCollectionViewController", bundle: nil)
let navVC = UINavigationController(rootViewController: vc)
appDelegate.window?.rootViewController = navVC

I have validated reads and writes to the synced Realm and found something peculiar: the realm seems to have a fileURL of null even when I'm able to write data successfully. I am accessing the realm in other parts of my app using
let realm = try! Realm()
and when I do
I always get nil, even for valid synced Realms.

So my question is, do I have to wait some period of time for the synced Realm to be accessible? If so, how would I go about doing this? Any help on this issue would be much appreciated.

Answer Source

It's expected that the fileURL of a synced Realm's configuration be nil, since the file location is managed my Realm and inaccessible to the user (you).

When opening a synced Realm for the first time on a device, the Realm will be accessible as soon as a valid SyncUser exists, provided by the SyncUser.authenticate(...) callback. However, its contents will be populated asynchronously, which is why realm.objects(Dot.self) is empty when immediately opening the Realm, but later gets the objects from the server.

If it's important to wait for that data to be available before proceeding with a part of your app, there are two ways Realm is working on to do that in the near future:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download