检查firebase DB中是否存在用户名。

时间:2016-03-04 17:30:15

标签: ios swift firebase

我正在尝试通过UI从@IBAction获取用户的用户名。

我的目标是检查Firebase中是否已存在用户名。如果它不存在,则注册它。如果确实存在,我想做其他一些事情。

这是我的代码。

@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
        }
    })
}

我遇到的问题是,如果用户名是唯一的(不存在),那么if / else的BOTH打印语句正在运行。 输出: 第一块 第二块

如果名称不唯一,则正确地跳过if / else的if部分。

为什么if / else语句的两个部分都在运行?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

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.

This triggers the callback again, which this time, will run through the else block.

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.