Firebase Swift检查用户(如果存在)无法正常运行 [英] Firebase Swift check user if exists not working properly
问题描述
我正在尝试检查数据库中是否存在用户,但是无论该用户是否存在,它总是显示成功".我不太了解FireBase文档,它们相当差劲,有人可以帮助我,告诉我为什么每次都能获得成功吗?
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!)
}
}
推荐答案
从Firebase加载数据是异步进行的.这意味着打印成功的代码将在实际加载数据之前运行.最简单的方法是使用一些适当的日志语句:
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
附加观察者之后
数据已加载
无法更改此行为.这只是大多数现代网络的工作方式.
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!)
}
})
这篇关于Firebase Swift检查用户(如果存在)无法正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!