使用Swift在Firebase数据库中找不到用户名

时间:2018-10-25 21:31:15

标签: ios swift firebase

我正在尝试检查我的Firebase数据库,以查看数据库中是否已有用户名。不幸的是,当我使用已经保存在其中的用户名时,不会让我知道。下面的代码。

@objc func pushedToRegister(_ sender: SignInSignUpButtons) {
    checkUserNameAlreadyExist()

    Auth.auth().createUser(withEmail: email.text!, password: password.text!, completion: { (user, error) in
        if error != nil {
            self.errorMessage = (error?.localizedDescription)!
            print(error!)
            self.showErrorView(forReason: 0)
            return
        }
        else {
            print("Registration was successful!")
            //Here we should go back to the home screen where the message at the top should say welcome back USER!

            if let userID = user?.user.uid {

                //Create User Profile

                let databaseRef = Database.database().reference()
                let usersRef = databaseRef.child("Users").child(userID)

                let usernameValue = ["username":self.username.text]

                usersRef.updateChildValues(usernameValue, withCompletionBlock: { (err, ref) in

                    if err != nil {
                        print(err!.localizedDescription)
                        self.showErrorView(forReason: 2)
                        return
                    }

                    //Profile created and updated!
                    self.navigationController?.popViewController(animated: true)

                })

            }
        }
    })

}

func checkUserNameAlreadyExist() {

    let ref = Database.database().reference()

    var usernameTaken = false
    ref.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.exists(){
            usernameTaken = true
            print("username taken")
        }else{
            usernameTaken = false
            print("username available")
        }
    }) { error in
        print(error.localizedDescription)
    }

    if usernameTaken == false{
        //do stuff with unique username
    }
}

不幸的是,每次我输入相同的用户名时,它每次都可以创建一个新的配置文件。它并没有提醒我用户名已被使用的事实。

1 个答案:

答案 0 :(得分:2)

Firebase函数是异步的,因此它们不会阻止其余代码的运行。如果您希望代码等待函数完成,则一种选择是使用闭包。您可以查看我关于封闭的blog post来查看一些示例。

此外,显示的代码实际上并未做任何事情来阻止该功能的其余部分运行。您需要编写某种条件来处理该问题。例如,您可以在完成处理程序中使用布尔值,如下所示:

func checkUserNameAlreadyExist(completion: @escaping (Bool) -> Void) {
    let ref = Database.database().reference()
    ref.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.exists() {
            usernameTaken = true
            print("username taken")
            completion(true)
        } else {
            usernameTaken = false
            print("username available")
            completion(false)
        }
    }) { error in
        print(error.localizedDescription)
        completion(true)
    }
}

然后在pushToRegister中,在继续操作之前检查布尔值是否为真。

@objc func pushedToRegister(_ sender: SignInSignUpButtons) {
    checkUserNameAlreadyExist() { isTaken in
        if (isTaken == true) {
            // show some message to the user
            return
        }
        Auth.auth().createUser(withEmail: email.text!, password: password.text!, completion: { (user, error) in
            if let error = error {
                self.errorMessage = error.localizedDescription
                print(error)
                self.showErrorView(forReason: 0)
                return
            }
            print("Registration was successful!")
            //Here we should go back to the home screen where the message at the top should say welcome back USER!
            if let userID = user?.user.uid {

                //Create User Profile
                let databaseRef = Database.database().reference()
                let usersRef = databaseRef.child("Users").child(userID)
                let usernameValue = ["username":self.username.text]
                usersRef.updateChildValues(usernameValue, withCompletionBlock: { (err, ref) in
                    if let err = err {
                        print(err.localizedDescription)
                        self.showErrorView(forReason: 2)
                        return
                    }

                    //Profile created and updated!                       
                    self.navigationController?.popViewController(animated: true)

                })
            }
        })
    }
}