I do this next way:
The function of register:
@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)
}
My User class function. It's API like class:
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
})
}
In your way you should swap login with username.
Hope it helps