Search code examples
iosswiftrealmnsuserdefaults

Can I use Realm for all data storage, or should I use NSUserDefaults for storing username/password?


I have an application which has a username/password login. Once logged in, the user should remain logged in until they log out, i.e. the user remains logged in even if they have no connection.

Currently I am authenticating the user, but I am unable to keep them logged in. Should I store the user details in NSUserDefaults for logging in on launch, or is there a way of keeping the user logged in using just Realm?

Thanks in advance!

SyncUser.logIn(with: userCredentials, server: (url! as URL)) { user, error in
    guard user != nil else {
        // Handles error
    }
    DispatchQueue.main.async {
        let configuration = Realm.Configuration(
            syncConfiguration: SyncConfiguration(user: user!, realmURL: URL(string: "realm://127.0.0.1:9080/~/realmtasks")!)
        )
        Realm.Configuration.defaultConfiguration = configuration

        self.performSegue(withIdentifier: "logInSegue", sender: self)
    }
}

Update: Maybe the answer to my problem is Apple Keychain?


Solution

  • You should not store passwords or any sensitive information inside NSUserDefault, by using a simple file manager you can read all the data stored in it, it is really unsafe.
    you don't even need a database or sort of. The right place to store sensitive info is the keychain of your device.
    There are a lot of libs on github that can help you in using it.
    Pay attention that what you save inside the keychain will persist even after you remove the application.