Menu Docs
Página inicial do Docs
/ /
Atlas Device SDKs
/ /

Vincular identidades do usuário - Swift SDK

Nesta página

  • Visão geral
  • Exemplo
  • Exemplo de assíncrono/aguardação

Atlas App Services provides many authentication providers to log users into your app. Each provider creates a unique user identity. App Services and the Realm Swift SDK lets you merge multiple credentials into one user identity.

Considere um aplicativo que oferece login anônimo. Isso permite que os usuários naveguem pelo aplicativo sem se registrar. Se os usuários gostariam do aplicativo, eles criarão contas permanentes. Eles se inscrevem com SSO ou autenticação por e-mail/senha. Por padrão, isso cria um novo objeto User . O aplicativo deve vincular a nova identidade ao usuário original.

Você pode vincular identidades usando linkUser(credentials:Credentials) . Isso vincula os provedores de autenticação a um objeto User conectado.

@interface LinkIdentitiesExample : NSObject
@end
@implementation LinkIdentitiesExample {
RLMApp *app;
RLMUser *anonymousUser;
}
// Entry-point for example.
- (void)runExample {
app = [RLMApp appWithId:YOUR_APP_ID];
[self logInAnonymously];
}
- (void)logInAnonymously {
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
if (error != nil) {
NSLog(@"Failed to log in: %@", [error localizedDescription]);
return;
}
// User uses app, then later registers an account
[self registerNewAccountAsAnonymousUser: user];
}];
}
- (void)registerNewAccountAsAnonymousUser:(RLMUser *)user {
NSString *email = @"link2@example.com";
NSString *password = @"ganondorf";
[[app emailPasswordAuth] registerUserWithEmail:email password:password completion:^(NSError *error) {
if (error != nil) {
NSLog(@"Failed to register new account: %@", [error localizedDescription]);
return;
}
// Successfully created account, now link it
// with the existing anon user
[self linkUser:self->anonymousUser withCredentials:[RLMCredentials credentialsWithEmail:email password:password]];
}];
}
- (void)linkUser:(RLMUser *)user withCredentials:(RLMCredentials *)credentials {
[[app currentUser] linkUserWithCredentials:credentials completion:^(RLMUser *user, NSError *error) {
if (error != nil) {
NSLog(@"Failed to link user: %@", [error localizedDescription]);
return;
}
NSLog(@"Successfully linked user: %@", user);
}];
}
@end
let app = App(id: YOUR_APP_SERVICES_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()

Novidade na versão 10.16.0.

O Realm Swift SDK fornece uma versão async/await do User.linkUser.

let app = App(id: YOUR_APP_SERVICES_APP_ID)
func logInAnonymously() async throws -> User {
let anonymousUser = try await app.login(credentials: Credentials.anonymous)
// User uses app, then later registers an account
let newAccountLinkedUser = try await registerNewAccount(anonymousUser: anonymousUser)
return newAccountLinkedUser
}
func registerNewAccount(anonymousUser: User) async throws -> User {
let email = "swift-async-link@example.com"
let password = "ganondorf"
try await app.emailPasswordAuth.registerUser(email: email, password: password)
// Successfully created account, now link it
// with the existing anon user
let linkedUser = try await link(user: anonymousUser, with: Credentials.emailPassword(email: email, password: password))
return linkedUser
}
func link(user: User, with credentials: Credentials) async throws -> User {
try await user.linkUser(credentials: credentials)
}
do {
let linkedUser = try await logInAnonymously()
print("Successfully linked user async: \(linkedUser)")
} catch {
print("Failed to link user: \(error.localizedDescription)")
}

A partir das versões 10.15.0 e 10.16.0 do SDK do Realm Swift, muitas das APIs do Realm suportam a sintaxe async/await do Swift. Os projetos devem atender a estes requisitos:

Versão do Swift SDK
Requisito de versão do Swift
Sistema operacional compatível
10.25.0
Swift 5.6
iOS 13.x
10.15.0 ou 10.16.0
Swift 5.5
iOS 15.x

Se a sua aplicação acessar Realm em um contexto do async/await, marque o código com @MainActor para evitar falhas relacionadas a threading.

Voltar

Aplicações multiusuário

Próximo

Criar e gerenciar chaves de API do usuário