Search code examples
realmrealm-mobile-platform

Sync Authentication in Realm Swift Version 2.0.4


I upgraded to Realm 2.0.4 in my Swift project and now the authenticate method doesn't work. I can't create new users or sign in to my Realm sync server anymore.

What changed?


Solution

  • There were some breaking changes in Realm Swift 2.0.4 and there is now a single SyncUser.logIn method to use. Whether you sign in or sign up is determined by the kind of SyncCredentials you pass in.

    Here's an example using Swift 3.0.1:

    //Create Account
    let signUpCredentials = SyncCredentials.usernamePassword(username: "username", password: "password", register: true)
    
    SyncUser.logIn(with: signUpCredentials, server: serverURL) { user, error in
      if user == nil {
        //Error
      }else{
        //Success
      }
    }
    
     //Log in
     let logInCredentials = SyncCredentials.usernamePassword(username: "username", password: "password")
    
     SyncUser.logIn(with: logInCredentials, server: serverURL) { user, error in
      if user == nil {
        //Error
      }else{
        //Success
      }
    }
    

    Note how the register flag is added for account creation. This code is easier to understand and more DRY than the old way, so kudos to the Realm Swift team.

    I hope this helps someone else.