Firebase查询唯一的用户名swift

我search了这个问题,但是他们都没有为我工作的答案。

我想这样做,当用户注册一个帐户,它会检查,看他们已经input的用户名已经存在,然后创build帐户。 我曾尝试在firebase中使用查询,但我似乎无法得到它的工作。

以下是我的Firebase数据的图像: 我的Firebase数据树

我将如何使用查询来查找关键字“用户名”的string?

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

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

现在只需在创build新用户时调用该函数即可:

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

这是我如何做到的:

 var text = "Your username" let dbRef = FIRDatabase.database().reference().child("users") dbRef.queryOrdered(byChild: "name").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { // Name doesn't exist } if let data = snapshot.value as? [String: [String: String]] { // it should exist if it reaches here } }) 

确保在数据库规则中为“性能”优化索引“name”上的“用户”节点。

我这样做下一步:

寄存器的function:

 @IBAction func signUpButtonTapped(_ sender: Any) { User.getItemByLogin(for: userLogin.text!, completion: { userItem in if userItem == nil { self.createAndLogin() } else { self.showAlertThatLoginAlreadyExists() } }) } private func createAndLogin() { FIRAuth.auth()!.createUser(withEmail: userEmail.text!, password: userPassword.text!) { user, error in if error == nil { // log in FIRAuth.auth()!.signIn(withEmail: self.userEmail.text!, password: self.userPassword.text!, completion: { result in // create new user in database, not in FIRAuth User.create(with: self.userLogin.text!) self.performSegue(withIdentifier: "fromRegistrationToTabBar", sender: self) }) } else { print("\(String(describing: error?.localizedDescription))") } } private func showAlertThatLoginAlreadyExists() { let alert = UIAlertController(title: "Registration failed!", message: "Login already exists.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } 

我的用户类function。 像类一样的API:

 static func getItemByLogin(for userLogin: String, completion: @escaping (_ userItem: UserItem?) -> Void) { refToUsersNode.observeSingleEvent(of: .value, with: { snapshot in for user in snapshot.children { let snapshotValue = (user as! FIRDataSnapshot).value as! [String: AnyObject] let login = snapshotValue["login"] as! String // getting login of user if login == userLogin { let userItem = UserItem(snapshot: user as! FIRDataSnapshot) completion(userItem) return } } completion(nil) // haven't founded user }) } 

在你的方式你应该交换username login

希望能帮助到你