繁体   English   中英

如何在Firebase数据库中检查唯一的用户名(Swift)

[英]How to check unique username in Firebase Database (swift)

我有Firebase数据库,其中每个用户都有自己的电子邮件和用户名。 如何检查唯一的用户名? 我试图这样做,但是我的代码无法正常工作,因此不同的用户可以使用相同的用户名

  usernameField.isHidden = false
    let username:String = self.usernameField.text!

    if (usernameField.text?.isEmpty == false){
    ref.child("users").queryOrdered(byChild("username").queryEqual(toValue: username).observeSingleEvent(of: .value, with: { snapshot in

            if snapshot.exists(){

                print("username exist")

            }else{

                ref.root.child("users").child(userID).updateChildValues(["username": username])
            }

        })
}

在此处输入图片说明

我在Firebase中有点新手,我为每个用户存储电子邮件和用户名,例如newUserReference.setValue(["username":String(), "email" : self.emailTextField.text!]) 在下一个视图上,用户可以在usernameField.text键入username ,并且该值将添加到Firebase数据库中。 但是,如果下一个用户(用户2)将输入与上一个用户相同的用户名,则必须将其阻止,因为用户名应唯一

如果您尝试在登录时存储用户的ID,请在收到成功的登录响应后执行以下操作:

创建一个共享实例来存储ID

class userDataSource {
    var id : String? // variable to store your users ID
    static let sharedInstance = PageDataSource() // global access to this dataSource
    private init() {}
}

成功登录后为id分配一个值

func getIDFromLogin() {
    if let user = Auth.auth().currentUser {
        print(user.uid)
        userDataSource.sharedInstance.id = user.uid
    }
}

然后,您可以执行以下操作以查看每个ID:

 ref.child("users").observeSingleEvent(of: .value, with: { snapshot in
     if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
         for snap in snapshots {
             print(snap.key) // you can compare userDataSource.sharedInstance.id to this value
         } 
     }     
 })

或者,如果您只想要该用户的数据,请执行以下操作:

ref.child("users").child(userDataSource.sharedInstance.id!).observeSingleEvent(of: .value, with: { snapshot in
     if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
             for snap in snapshots {
                 print(snap) 
         } 
     }     
 })

编辑以更准确地回答您的问题

这是一个更符合您问题的答案。 我将建议的第一件事是为您向Firebase添加一个表,该表仅包含用户名以及它们所属的.uid 您将需要先通读该表以确保没有其他人拥有该用户名,然后相应地更新该表:

// This function will check through all of the usernames and return a true or false value in the completion handler
func checkUsernames(_ completion: @escaping(_ success: Bool) -> Void) {
    ref.child("usernames").observeSingleEvent(of: .value, with: { snapshot in
        if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
            for snap in snapshots {
                if snap.value == username {
                    completion(false)
                }
            }
            completion(true) 
        } else {
            completion(true) // TODO: check for errors before setting completion
        }     
    })
}

// this function will set the username values in Firebase
func storeUsername() {
    let usernameRef = ref.child("usernames")
    usernameRef.updateChildValues(["\(userDataSource.sharedInstance.id!)" : username])
        }
    }
}

假设您已经处理了username变量并设置了它的值,则将调用以下函数:

checkUsernames({ (success) in
    if success {
        storeUsername()
        // you may also want to update your "users" table here as well
    } else { print("Duplicate Username") } // handle alert or something here
})

您仍然需要使用queryOrdered(byChild:)指示要排序/过滤的属性:

if (usernameField.text?.isEmpty == false){
    ref.child("users").queryOrdered(byChild:"username").queryEqual(toValue: username).observeSingleEvent(of: .value, with: { snapshot in

        if snapshot.exists(){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM