Search code examples
swiftrealmrealm-mobile-platform

When do I have to connect to realm object server in my swift code with regards to controllers, functions and queries


Currently I am using this code from the realm webpage to connect to the realm mobile server.

func setupRealm() {
        // Log in existing user with username and password
        let username = "admin"  // <--- Update this
        let password = "admin"  // <--- Update this

        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)
            }
        }
    }

In my code when and where do I have to use this connection. My current observation is:

1, in the ViewController in every function of viewDidLoad, viewWillAppear, etc I have to run the above code

  1. before every query I have to run the code again

Is there a clever way of only having to connect once for the whole project or once for the whole ViewController? This is to consider that I am updating and querying the realm mobile database in different ViewControllers in different functions.


Solution

  • It shouldn't be necessary for you to log in the user any more than once per application session at most.

    I recommend you create a manager class, perhaps a singleton or otherwise an instance you can pass throughout your app, that handles acquiring and holding on to the user object. This manager can be instantiated when your application launches.

    If your user hasn't yet logged in before ever, or has previously logged out, once they enter their credentials you can then make the SyncUser.logIn() call to get the user. Once you have the user you can store it in the manager. Your view controllers can then ask this manager for the user object so they can use it to open their Realms.

    If your user has logged in before, you can simply get the user (which is persisted between app launches) through SyncUser.current. The manager can handle deciding between getting the user by logging in and getting it from SyncUser.current so your view controllers don't need to concern themselves with this detail.

    Another possible feature you might want to build is a way for view controllers who want a user to register on the manager to be notified if a user is logged in, so they can immediately open up Realms and perform other work.