问题
I'm trying to check if a user exists in my database but it always says "Success" no matter if the user exists or not. I don't really understand FireBase docs, they are pretty poor, can anyone help me and tell me why I get success everytime?
if nickTextField.text != "" {
let db = Database.database().reference()
var userExistsSwitch = false
db.child("Usernames").observe(.value, with: { (snapshot) in
if snapshot.hasChild("\(self.nickTextField.text!)") {
userExistsSwitch = true
print("Username already exists!")
}
})
db.child("Usernames").removeAllObservers()
if !userExistsSwitch {
print("Success!")
db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
}
}
回答1:
Loading data from Firebase happens asynchronously. This means that your code that prints success runs before the data has actually loaded. The easiest way to see this is with a few well places log statements:
let db = Database.database().reference()
print("Before attaching observer");
db.child("Usernames").observe(.value, with: { (snapshot) in
print("Data has loaded");
})
print("After attaching observer");
When you run this code, it prints:
Before attaching observer
After attaching observer
Data has loaded
There is no way to change this behavior. It is simply the way most of the modern web works.
This means that you'll have to put any code that requires the data into the completion handler, or call it from within the completion listener. An easy way to do this in your case:
let db = Database.database().reference()
var userExistsSwitch = false
db.child("Usernames").observe(.value, with: { (snapshot) in
db.child("Usernames").removeAllObservers()
if snapshot.hasChild("\(self.nickTextField.text!)") {
userExistsSwitch = true
print("Username already exists!")
}
if !userExistsSwitch {
print("Success!")
db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
}
})
来源:https://stackoverflow.com/questions/47542744/firebase-swift-check-user-if-exists-not-working-properly