Swift Firebase Check If User Exists

Swift Firebase Check if user exists

I would suggest moving the code out of the app delegate and into an initial viewController. From there establish if this is an existing user and send the user to the appropriate UI.

.observeSingleEvent loads all of the nodes at a given location - one use would be to iterate over them to populate a datasource. If there were 10,000 users they would all be loaded in if you observe the /users node.

In this case it's really not necessary. It would be better to just observe the single node you are interested in and if it exists, send the user to a UI for existing users.

here's the code to do that

    if let user = Auth.auth().currentUser {
let ref = self.ref.child("users").child(user.uid)
ref.observeSingleEvent(of: .value, with: { snapshot in
self.presentUserViewController(existing: snapshot.exists() )
})
}

snapshot.exists will be either true if the user node exists or false if not so the function presentUserViewController would accept a bool to then set up the UI depending on the user type.

Checking if User Exists in Firebase doesn't Work - Swift

You'll want to attach the database listener inside the auth state changed listener, so that it only runs once the user is authenticated:

Auth.auth().addStateDidChangeListener { auth, user in
if user != nil {
let ref = self.ref.child("users").child(user.uid)
ref.observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exists() {
// TODO: a user is signed in and registered, navigate to the next screen for them
self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: nil)
}
else {
// TODO: a user is signed in and not registered, navigate to the next screen for them
}
})
}
else{
self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
}
}

Check if user exist with firebase 3.0 + swift

I figured out I need to change the .Value to FIRDataEventType.Value

 if (usernameTextField.text?.isEmpty == false){
let databaseRef = FIRDatabase.database().reference()

databaseRef.child("Users").observeSingleEventOfType(FIRDataEventType.Value, withBlock: { (snapshot) in

if snapshot.hasChild(self.usernameTextField.text!){

print("true rooms exist")

}else{

print("false room doesn't exist")
}

})

Google sign in using firebase to check user already exists

I think to check if a user exists you can use a method fetchSignInMethods.

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

if let error = error {
// ...
return
}

guard let authentication = user.authentication else { return }

guard let email = user.profile.email else { return }

Auth.auth().fetchSignInMethods(email: email) { (providers, error) in
if let error = error {
print(error)
return
}

if let providers = providers {
//This returns an array and will tell you if an user exists or not
//If the user exists you will get providers.count > 0 else 0

if providers.count > 0 {
//User Exists and you can print the providers like [google.com, facebook.com] <-- Providers used to sign in
} else {
//Show Alert user does not exist
}
}

}

}

check if the username exist in Firebase

The easiest way of achieving this is when registering a user, create the user with their unique UID and save all their data inside there like you're doing BUT also create a node called "usernames" that simply holds all the usernames that are signed up with the key as their username and the value as 1 like so:

Usernames {
- username: 1
}

When a user signs up and then goes to enter a username, you can check if it exists like so:

let username = "username that user has typed in"

let reference = Database.database().reference()
reference.child("usernames").observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.hasChild(username) {

print("Already exists")

} else {

print("Doesn't exist")

}

}, withCancel: nil)

EDIT:

Thanks to @FrankvanPuffelen, here's a much more efficient way of doing this - without looping through every single username.

let reference = Database.database().reference()
reference.child("usernames").child(username).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists() {

print("Username already exists")

} else {

print("Username doesn't already exist")

}

}, withCancel: nil)

How to check if email already exist before creating an account (Swift)

How I create user accounts

This is an example of what I use. When a user provides credentials, FirebaseAuth checks if these credentials can be used to make a user account. The function returns two values, a boolean indicating whether the creation was successful, and an optional error, which is returned when the creation is unsuccessful. If the boolean returns true, we simply push to the next view controller. Otherwise, we present the error.

func createUserAcct(completion: @escaping (Bool, Error?) -> Void) {

//Try to create an account with the given credentials
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordConfirmTextField.text!) { (user, error) in
if error == nil {

//If the account is created without an error, then we will make a ProfileChangeRequest, i.e. update the user's photo and display name.
if let firebaseUser = Auth.auth().currentUser {

let changeRequest = firebaseUser.createProfileChangeRequest()
//If you have a URL for FirebaseStorage where the user has uploaded a profile picture, you'll pass the url here
changeRequest.photoURL = URL(string: "nil")
changeRequest.displayName = self.nameTextField.text!
changeRequest.commitChanges { error in
if let error = error {
// An error happened.
completion(false, error)
} else {
//If the change is committed successfully, then I create an object from the credentials. I store this object both on the FirebaseDatabase (so it is accessible by other users) and in my user defaults (so that the user doesn't have to remotely grab their own info

//Create the object
let userData = ["email" : self.emailTextField.text!,"name": self.nameTextField.text!] as [String : Any]

//Store the object in FirebaseDatabase
Database.database().reference().child("Users").child(firebaseUser.uid).updateChildvalues(userData)
//Store the object as data in my user defaults
let data = NSKeyedArchiver.archivedData(withRootObject: userData)
UserDefaults.standard.set(data, forKey: "UserData")
UserDefaults.standard.set([Data](), forKey: "UserPhotos")
completion(true, nil)
}
}
}
} else {
// An error happened.
completion(false, error)
}
}
}

Here is an example of how I would use it. We can use the success boolean returned to determine if we should push to the next view controller, or present an error alert to the user.

createUserAcct { success, error in
//Handle the success
if success {
//Instantiate nextViewController
let storyboard = UIStoryboard(name: "Main", bundle: .main)
let nextVC = storyboard.instantiateViewController(withIdentifier: "NextVC") as! NextViewController

//Push typeSelectVC
self.navigationController!.pushViewController(viewController: nextVC, animated: true, completion: {
//We are no longer doing asynchronous work, so we hide our activity indicator
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
})
} else {
//We now handle the error
//We are no longer doing asynchronous work, so we hide our activity indicator
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()

//Create a UIAlertController with the error received as the message (ex. "A user with this email already exists.")
let alertController = UIAlertController(title: "Error", message: error!.localizedDescription, style: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, action: nil)

//Present the UIAlertController
alertController.addAction(ok)
self.present(alertController, animated: true, completion: nil)
}

}

Let me know if this all makes sense, I know there is a lot to it. I'm just considering things you'll maybe find you need done anyways that you may not be aware of (like making change requests, or storing a data object on FirebaseDatabase).

Now for checking if the email is already taken:

Remember when I said that I post a user object to FirebaseDatabase upon account creation? Well we can query for the given email to see if it already exists. If it doesn't we continue with the flow as normal, without having actually created the account. Otherwise, we simply tell the user to pick another email address.

Pushing a user object to your database (taken from the above code):

if let firebaseUser = Auth.auth().currentUser {
//Create the object
let userData = ["email" : self.emailTextField.text!,"name": self.nameTextField.text!] as [String : Any]

//Store the object in FirebaseDatabase
Database.database().reference().child("Users").child(firebaseUser.uid).updateChildvalues(userData)
}

And now querying to see if somebody already has that email:

func checkIfEmailExists(email: String, completion: @escaping (Bool) -> Void ) {

Database.database().reference().child("Users").queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .value, with: {(snapshot: DataSnapshot) in

if let result = snapshot.value as? [String:[String:Any]] {
completion(true)
} else {
completion(false)
}
}
}

Then we can call this like so:

checkIfEmailExists(email: emailTextField.text!, completion: {(exists) in 
if exists {
//Present error that the email is already used
} else {
//Segue to next view controller
}
})


Related Topics



Leave a reply



Submit