我正在使用Facebook和Google登录协议登录我的用户。我可以通过以下方式存储这些用户:
let firebaseID = Auth.auth().currentUser?.uid
let userID = user.userID
let fullName = user.profile.name
let email = user.profile.email
let provider = "Google"
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
let databaseRef = Database.database().reference()
let key = databaseRef.child("node").childByAutoId().key
let userInfo = ["UID": userID,
"Full Name": fullName,
"Email": email,
"Provider": provider]
let childUpdates = ["/Users/\(key)/": userInfo]
databaseRef.updateChildValues(childUpdates)
每次登录时,即使使用相同的凭据,也会使用相同的登录用户创建一个新用户。如果特定用户之前已经登录,如何防止创建新实例。
答案 0 :(得分:2)
您应该使用
let childUpdates = ["/Users/\(userID)/": userInfo]
,这样就不会出现可选内容,您应该这样让
key = databaseRef.child("node").childByAutoId().key ?? ""
因为当同一用户进入时用户ID不会更改,并且您每次输入用户都使用自动键,所以每次都会创建一个新子代
答案 1 :(得分:1)
您应该在 signInAndRetrieveData 之后检查用户是否已注册:
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error {
return
}
if(isNewUser()) {
// create new user in Firebase
}
else {
// continue and skip creating user ..
}
}