以下是我对如何使用Firebase匿名身份验证的建议:
-
一旦你的应用程序启动,初始化Firebase并检查
一
用户已登录。如果用户之前已登录,Firebase Auth将在您调用此方法之前及时获取该用户。
-
如果没有用户,请匿名登录。
-
然后,您可以开始使用受益于登录用户的所有Firebase服务(如Firestore)
-
一旦用户决定实际登录,使用任何Firebase身份验证提供程序获取令牌,并将其链接到现有的匿名用户。顺便说一句,我建议使用比电子邮件/密码更安全的东西。
在应用程序启动时执行匿名登录的示例代码(取自
this sample app
):
func signIn() {
if Auth.auth().currentUser == nil {
Auth.auth().signInAnonymously()
}
}
升级到Apple帐户登录的示例代码(取自
the same sample app
):
case .link:
if let currentUser = Auth.auth().currentUser {
currentUser.link(with: credential) { (result, error) in
if let error = error, (error as NSError).code == AuthErrorCode.credentialAlreadyInUse.rawValue {
print("The user you're signing in with has already been linked, signing in to the new user and migrating the anonymous users [\(currentUser.uid)] tasks.")
if let updatedCredential = (error as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as? OAuthCredential {
print("Signing in using the updated credentials")
Auth.auth().signIn(with: updatedCredential) { (result, error) in
if let user = result?.user {
currentUser.getIDToken { (token, error) in
if let idToken = token {
(self.taskRepository as? FirestoreTaskRepository)?.migrateTasks(from: idToken)
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
}
}
else if let error = error {
print("Error trying to link user: \(error.localizedDescription)")
}
else {
if let user = result?.user {
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
如果您对Combine的情况感兴趣,我们已经开始为Firebase实现Combine支持-查看我们的
project tracker