使用 SwiftUI、Xcode12.5.1、Swift5.4.2、iOS14.7.1、
我的 Firebase-Login 页面应扩展为其他登录可能性,例如 Apple-Login(最终是 Google-login、Facebook-login 等)。
我有一个运行良好的 Firebase-Login 实现。
Sign in with Apple
我用Button扩展了 LoginView 。
这个新的 Apple 登录在其基本实现中也有效。
现在的问题:
如果我使用 Apple 登录,我需要访问相应的 Firebase 用户才能查询正确的用户数据。现在,使用 Apple 登录可以工作,但检索到的数据不是相应 Firebase 用户的用户数据。
我想要达到的目标:
从注销状态,我想
a) 能够使用 Firebase 电子邮件/密码登录,但有时想要注销并再次使用 Apple 登录。
--> 对于这两种情况,我都想获得相同的用户数据
b) 能够使用 Apple 登录,但有时想退出并使用 Firebase 电子邮件/密码再次登录
--> 对于这两种情况,我都想获得相同的用户数据
--- 理念 ----------
我从Firebase 文档中了解到,有一种方法可以连接link
两个登录帐户,我们可以知道这两个帐户是对应的。
--- 实施 -----------
以下是我当前对 Apple 登录的实现:
了解到可以在-callback的错误中获取对应其他账号的userInformation link
。但就我而言,我得到了错误的链接错误:
我的链接错误:
The email address is already in use by another account.
代替:
AuthErrorCode.credentialAlreadyInUse
对我来说这没有意义。特别是因为我知道我之前已经使用 Firebase-Email/Password 登录过。然后我注销了,现在我尝试使用 Apple 登录。
该方法是否应该link
识别出我之前被允许通过 Firebase-Email/Password 登录,并且之前使用该电子邮件是否可以?我不明白这个链接错误。
问题:
在-callback 中
link
,为什么我得到的是 linkErrorThe email address is already in use by another account.
而不是AuthErrorCode.credentialAlreadyInUse
??为了使 a) 工作,我需要改变什么?
实现如何寻找 b) 工作流程(即,如果用户登录到 Apple,然后注销并使用 Firebase-Email/Password 再次登录??)。那我这两个账户怎么办
link
??
这是我的代码:
switch state {
case .signIn:
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
print("Error authenticating: \(error.localizedDescription)")
return
}
do {
if let email = try THKeychain.getEmail(),
let password = try THKeychain.getPassword() {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
if let user = authResult?.user {
user.link(with: credential) { (result, linkError) in
if let linkError = linkError, (linkError 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 [\(user.uid)] tasks.")
if let updatedCredential = (linkError 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 {
// eventually do a data-migration
user.getIDToken { (token, error) in
if let _ = token {
// do data migration here with the token....
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
}
}
else if let linkError = linkError {
// I END UP HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WHY WHY WHY WHY WHY WHY WHY WHY ????????????????????????
print("Error trying to link user: \(linkError.localizedDescription)")
}
else {
if let user = result?.user {
self.doSignIn(appleIDCredential: appleIDCredential, user: user)
}
}
}
}
}
} catch {
print(error.localizedDescription)
}
if let user = authResult?.user {
if let onSignedInHandler = self.onSignedInHandler {
onSignedInHandler(user)
}
}
}
case .link:
// t.b.d.
case .reauth:
// t.b.d.
}