[英]How can you check if a childByAutoID() already exists in the Firebase Realtime Database?
I am logging my users in with the Facebook and Google sign-in protocols.我正在使用 Facebook 和 Google 登录协议登录我的用户。 I am able to store these users by doing:
我可以通过执行以下操作来存储这些用户:
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)
Every time I sign in, even with the same credentials a new user is created with the same sign in user.每次我登录时,即使使用相同的凭据,也会创建一个具有相同登录用户的新用户。 How can I prevent a new instance from being created if a particular user has logged in before.
如果特定用户之前已登录,如何防止创建新实例。
you should use:你应该使用:
let childUpdates = ["/Users/\(userID)/": userInfo]
and so that the optional does not appear you should put it like this:为了不出现可选项,你应该这样写:
let key = databaseRef.child("node").childByAutoId().key ?? ""
or unwrap it if you want to catch/prevent nil或者如果你想捕捉/防止 nil 就打开它
let key = databaseRef.child("node").childByAutoId().key!
However, since the user id does not change when the same user enters new information, and you are using the autokey for every time the user enters, a new child is being created every time.但是,由于当同一用户输入新信息时用户 ID 不会更改,并且每次用户输入时都使用自动键,因此每次都会创建一个新子项。
You should check if user is already registered or no after signInAndRetrieveData :您应该在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 ..
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.