[英]Checking to see if username exists in firebase DB.
I am trying to get a username from the user via @IBAction from the UI. 我正在尝试通过UI中的@IBAction从用户获取用户名。
My goal is to check if the username already exists in Firebase. 我的目标是检查用户名是否已在Firebase中存在。 If it does not exists, then register it.
如果不存在,请注册。 If it does exist, I would like to do some other stuff.
如果确实存在,我想做一些其他的事情。
Here is my code. 这是我的代码。
@IBAction func enterUsername(){
let enteredUsername = usernameText!.text!
let namesRef = ref.childByAppendingPath("/usernames/\(enteredUsername)")
namesRef.observeEventType(.Value, withBlock: {
snap in
if (snap.value is NSNull){
let userNameAndUUID = ["Username" : enteredUsername, "UUID" : self.appDelegate.UUID]
namesRef.setValue(userNameAndUUID)
print("first block")
}else {
print("second block")
//do some other stuff
}
})
}
The problem I am having , is that IF the username is unique (does not exist) then BOTH print statements of the if/else are running. 我遇到的问题是,如果用户名是唯一的(不存在),则if / else的两个打印语句都在运行。 Output: first block second block
输出:第一块第二块
If the name is NOT unique, it is properly skipping the if portion of the if/else. 如果名称不是唯一的,则它会正确跳过if / else的if部分。
Why are both sections of the if/else statement running? 为什么if / else语句的两个部分都运行?
Thanks for any help. 谢谢你的帮助。
The behavior you're seeing is indeed intended. 您所看到的行为确实是有意的。 Since you're attaching an observer, the first if block is being run for a unique name, but within that block, you're setting a value.
由于要附加观察者,因此第一个if块将以唯一的名称运行,但是在该块内,您需要设置一个值。
This triggers the callback again, which this time, will run through the else block. 这将再次触发回调,这一次将遍历else块。
The correct way to change this code is to use observeSingleEventOfType
, so that you only read the value once and do not observe it continuously. 更改此代码的正确方法是使用
observeSingleEventOfType
,以便您只读取一次该值,而不会连续观察它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.