检查用户名是否存在于Firebase中 [英] check if the username exist in Firebase

查看:109
本文介绍了检查用户名是否存在于Firebase中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据库

users/UID1/(用户1的用户名")

users/UID1/"Username" (of user 1)

 /UID2/"Username" (of user 2)
 /UID3/"Username" (of user 3)
 /UID4/"Username" (of user 4)

以此类推.

我想检查用户名是否存在,但我无法与所有现有的UID陷入循环. 目前,我已经尝试过:

I would like to check if the username exist but I don't manage to go in a loop with all existing UID. For now I have tried :

let databaseRef = Database.database().reference()        
            databaseRef.child("users").child("uid").child("Username").observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
                switch snapshot.value {
                case let value as Bool where value:
                    // value was a Bool and equal to true
                    print ("username found")
                default:
                    // value was either null, false or could not be cast
                    print ("username not found")
                }
            })

        }

我不知道要放置什么(而不是child("uid"))循环进入数据库中的每个uid并检查用户名是否存在

I don't know what to put instead of child("uid") to loop into every uid in my database and check if a username exists

感谢您的帮助!

推荐答案

最简单的方法是在注册用户时,使用其唯一的UID创建用户并将所有数据保存在其中,就像在执行BUT一样创建一个名为用户名"的节点,该节点仅保存所有使用键作为其用户名并将其值设置为1的用户名,如下所示:

The easiest way of achieving this is when registering a user, create the user with their unique UID and save all their data inside there like you're doing BUT also create a node called "usernames" that simply holds all the usernames that are signed up with the key as their username and the value as 1 like so:

Usernames {
 - username: 1
}

当用户注册然后输入用户名时,您可以像这样检查用户名是否存在:

When a user signs up and then goes to enter a username, you can check if it exists like so:

let username = "username that user has typed in"

let reference = Database.database().reference()
reference.child("usernames").observeSingleEvent(of: .value, with: { (snapshot) in

    if snapshot.hasChild(username) {

        print("Already exists")

    } else {

        print("Doesn't exist")

    }

}, withCancel: nil)

感谢@FrankvanPuffelen,这是一种更有效的方式-无需循环访问每个用户名.

Thanks to @FrankvanPuffelen, here's a much more efficient way of doing this - without looping through every single username.

let reference = Database.database().reference()
reference.child("usernames").child(username).observeSingleEvent(of: .value, with: { (snapshot) in

    if snapshot.exists() {

        print("Username already exists")

    } else {

        print("Username doesn't already exist")

    }

}, withCancel: nil)

这篇关于检查用户名是否存在于Firebase中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆