Navigation

Multi-User Applications - iOS SDK

The Realm SDK automatically adds users to a device when they log in for the first time on that device. When a user logs in, they immediately become the application's active user.

let app = App(id: YOUR_REALM_APP_ID)
let joeCredentials = Credentials.emailPassword(email: "joe@example.com", password: "passw0rd")
app.login(credentials: joeCredentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let joe):
// The active user is now Joe
assert(joe == app.currentUser)
}
}
let emmaCredentials = Credentials.emailPassword(email: "emma@example.com", password: "pa55word")
app.login(credentials: emmaCredentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let emma):
// The active user is now Joe
assert(emma == app.currentUser)
}
}

You can access a list of all user accounts that are stored on the device. This list includes all users that have logged in to the app on a given device regardless of whether they are currently authenticated.

let app = App(id: YOUR_REALM_APP_ID)
let users = app.allUsers
users.forEach({ (key, user) in
print("User: \(key) \(user)")
})

You can change an app's active user to another logged in user at any time with the following code:

let app = App(id: YOUR_REALM_APP_ID)
// ... log in ...
// Get another user on the device, for example with `app.allUsers`
let secondUser: User = getSomeOtherUser()
XCTAssertNotEqual(app.currentUser, secondUser)
// assert(app.currentUser != secondUser)
// Switch to another user
// app.switch(to: secondUser)
// The switch-to user becomes the app.currentUser
// XCTAssertEqual(app.currentUser, secondUser)
// assert(app.currentUser == secondUser)

You can remove all information about a user from the device and automatically log the user out.

app.currentUser?.logOut { (error) in
// user is logged out or there was an error
}
Give Feedback