Swift 3, Xcode 8, RealmSwift 2.0.2, Realm Object Server 1.0
In my app delegate, I have a function that sets my Realm configuration to connect to a remote sync server I have set up. I'm just using a test account to authenticate until I can get the basics of sync working. 1.1.1.1
isn't my real IP address. ;)
let username = "test"
let password = "test"
let address = "http://1.1.1.1:9080"
let syncAddress = "realm://1.1.1.1:9080/~/myapp"
SyncUser.authenticate(with: Credential.usernamePassword(username: username, password: password, actions: []), server: URL(string: address)!, onCompletion: { user, error in
guard let user = user else {
fatalError(String(describing: error))
}
// Open Realm
Realm.Configuration.defaultConfiguration = Realm.Configuration(
syncConfiguration: (user, URL(string: syncAddress)!)
)
})
This seems to work fine. I see data appear on my server, and I get no errors. My assumption is that setting the Realm configuration here means that all instances of Realm()
will use this configuration.
I then set a realm
object as a class property in two separate view controllers:
class TableViewControllerA: UITableViewController{
let realm = try! Realm()
override func viewDidLoad() {
// CORRECT: Prints "nil" as it should for a remotely synced Realm instance
print(realm.configuration.fileURL)
}
}
...and another in another file:
class ViewControllerB: UIViewController{
let realm = try! Realm()
override func viewDidLoad() {
// WRONG: Prints the path to the local realm file in the Simulator
print(realm.configuration.fileURL)
}
}
As noted in the code comments above, the two instances of realm
are different. On some of my view controllers, I can save objects to the server and see them appear on my device. On other view controllers, I don't see any data because it's using the wrong Realm database.
Can I not reliably expect a Realm configuration to persist throughout my app? Do I need to do something else to use the same configuration?