使用Swift和Firebase检查用户是否存在用户名 [英] Check if user exists with username using Swift and Firebase

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

问题描述

我当前正在尝试编写一个函数,该函数可以在用户存在时传递用户数据.当用户名位于数据库中时,代码就可以了,但是如果数据库中没有记录用户名,我将不知道如何使用返回函数.

I'm currently trying to code a function who pass the user Data when user exists. When the username is in the database, the code is okay, but if there is no username recorded in the database I don't know how to have a return function.

我是初学者,这就是我所做的:

I'm beginner, this is what I did:

func observeUserByUsername(username: String, completion: @escaping (Userm?) -> Void) {
      REF_USERS.queryOrdered(byChild: "username_lowercase").queryEqual(toValue: username).observeSingleEvent(of: .childAdded) { (snapshot) in

         if let dict = snapshot.value as? [String: Any] {
            let user = Userm.transformUser(dict: dict, key: snapshot.key)
            completion(user)
         } else {
            print("no user")
            completion(nil)
         }
      }
}

我想要这样的东西:如果有使用此用户名的用户->返回nil(表示完成).

I would like to have something like this: if there is user with this username -> return nil (for the completion).

你知道我该怎么做吗?

推荐答案

因此,如果我理解正确,则只需要检查是否存在使用该用户名的用户即可.您只需输入firebase的路径,然后使用exist()方法检查此子节点是否存在.我有一个类似的方法,您可以更改它以适合您的项目.

So if I got it right, you want to just check if a user with the username exists. You can just enter the path to firebase and use the exists() method to check if this subnode exists. I have a similar method, you can maybe change it to fit into your project.

func checkUsernameAvailability(completion: @escaping (_ available:Bool)->()){
    guard let lowercasedText = usernameTextField.text?.lowercased() else {completion(false); return}
    let ref = Database.database().reference().child("users").child("username").child(lowercasedText)
    ref.observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.exists(){
            completion(false)
            return
        }else{
            completion(true)
        }
    }
}

请注意,Firebase不区分大小写(这就是为什么我总是检查并存储小写版本的原因).如果您的子节点例如是用户名",然后搜索名称用户名",它将告诉您已经有一个具有此名称的用户.

Be careful, Firebase is not case-sensitive (that's why I always check and also store the lowercased version). If your subnode e.g. is 'UserName' and you search for the name 'username' it will tell you that there is already one with this name.

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

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