Different Realm Configurations Appearing in Swift App

蓝咒 提交于 2019-12-08 11:39:53

问题


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?


回答1:


You're setting the default configuration within the authentication completion handler. This callback is invoked asynchronously after the user has been authenticated. If an instance of one of your view controller subclasses happens to be created before the callback runs, the Realm it opens will use the default default configuration, prior to any changes you make in your authentication completion handler.



来源:https://stackoverflow.com/questions/39927239/different-realm-configurations-appearing-in-swift-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!