Navigation

Link User Identities - iOS SDK

MongoDB Realm provides multiple ways for users to log into your application. Because each method of authentication corresponds to a unique user identity, Realm lets you merge multiple identities corresponding to a single user into one user identity.

For instance, consider an application that enables users to authenticate via anonymous authentication so they may explore functionality without linking to an existing SSO provider or generating a new password. When that user finally decides to create a full account with an SSO provider or email/password authentication, you need some way of persisting the user's original anonymous identity with their new permanent identity.

You can link identities using the linkUser(credentials:Credentials) method of the User object of a logged in User.

let app = App(id: YOUR_REALM_APP_ID)
func logInAnonymously() {
app.login(credentials: Credentials.anonymous) { (result) in
switch result {
case .failure(let error):
print("Failed to log in: \(error.localizedDescription)")
case .success(let user):
// User uses app, then later registers an account
registerNewAccount(anonymousUser: user)
}
}
}
func registerNewAccount(anonymousUser: User) {
let email = "swift-link@example.com"
let password = "ganondorf"
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
guard error == nil else {
print("Failed to register new account: \(error!.localizedDescription)")
return
}
// Successfully created account, now link it
// with the existing anon user
link(user: anonymousUser, with: Credentials.emailPassword(email: email, password: password))
}
}
func link(user: User, with credentials: Credentials) {
user.linkUser(credentials: credentials) { (result) in
switch result {
case .failure(let error):
print("Failed to link user: \(error.localizedDescription)")
case .success(let user):
print("Successfully linked user: \(user)")
}
}
}
logInAnonymously()
Give Feedback