Firebase 快速查询唯一用户名 [英] Firebase querying for unique Username swift

查看:27
本文介绍了Firebase 快速查询唯一用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了这个问题,但没有一个答案对我有用.

我想让它在用户注册帐户时,在创建帐户之前检查他们输入的用户名是否已经存在.我曾尝试在 firebase 中使用查询,但我似乎无法让它工作.

这是我的 firebase 数据的图像:我的 firebase 数据树

我将如何使用查询来查找键用户名"的字符串?

解决方案

你可以这样做,用完成块制作一个函数来检查用户名是否已经存在于你的 Firebase 数据库中,并在此基础上创建新用户

>

func checkUserNameAlreadyExist(newUserName: String, completion: @escaping(Bool) -> Void) {让 ref = FIRDatabase.database().reference()ref.child("users").queryOrdered(byChild: "username").queryEqual(toValue: newUserName).observeSingleEvent(of: .value, with: {(snapshot: FIRDataSnapshot) in如果快照存在(){完成(真)}别的 {完成(假)}})}

现在只需在创建新用户时调用此函数:

self.checkUserNameAlreadyExist(newUserName: "Johnson") { isExist in如果存在{print("用户名存在")}别的 {打印(创建新用户")}}

I searched for this question, but none of them had an answer that worked for me.

I want to make it so when a user registers an account, it checks to see if the username they have entered already exists, before creating the account. I have tried using querying in firebase, but I just can't seem to get it to work.

Here is an image of what my firebase data looks like: My firebase data tree

How would I use query to find the string for the key "username"?

解决方案

You can go like this, make one function with completion block to check username is already exist in your Firebase DB and create new user on the basis of it

func checkUserNameAlreadyExist(newUserName: String, completion: @escaping(Bool) -> Void) {

    let ref = FIRDatabase.database().reference()
    ref.child("users").queryOrdered(byChild: "username").queryEqual(toValue: newUserName)
              .observeSingleEvent(of: .value, with: {(snapshot: FIRDataSnapshot) in

        if snapshot.exists() {
            completion(true)
        }
        else {
            completion(false)
        }
    })
}

Now simply call this function when you create new user:

self.checkUserNameAlreadyExist(newUserName: "Johnson") { isExist in
    if isExist {
        print("Username exist")
    }
    else {
        print("create new user")
    }
}

这篇关于Firebase 快速查询唯一用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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