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.
check if username exists in firestore and return true swiftUI
You can use a boolean variable to check if you have found a matching name, and you can set it to true if you find a match.
You can use the following code:
func checkUsername(username: String, completion: @escaping (Bool) -> Void) {
// Get your Firebase collection
let collectionRef = db.collection("users")
// Get all the documents where the field username is equal to the String you pass, loop over all the documents.
collectionRef.whereField("username", isEqualTo: username).getDocuments { (snapshot, err) in
if let err = err {
print("Error getting document: \(err)")
} else if (snapshot?.isEmpty)! {
completion(false)
} else {
for document in (snapshot?.documents)! {
if document.data()["username"] != nil {
completion(true)
}
}
}
}
}
Swift & Firebase | Checking if a user exists with a username
Easy fix:
Don't use .childAdded as the block will not execute when the query doesn't find anything.
Instead use .Value and check for NSNull
let checkWaitingRef = Firebase(url:"https://test.firebaseio.com/users")
checkWaitingRef.queryOrderedByChild("username").queryEqualToValue("\(username!)")
.observeEventType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found)")
} else {
print(snapshot.value)
}
})
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)
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")
}
})
Check if username already exist's : Swift, Firebase
Modify your JSON tree to include a separate node active_usernames
, in that add username of every user whenever you create new user, modify whenever your user modify its username...
myApp:{
users:{
uid1:{....},
uid2:{....},
uid3:{....},
uid4:{....},
}
active_usernames :{
uid1username : "true",
uid2username : "true",
uid3username : "true",
uid4username : "true"
}
}
To check your if username already exists:-
//Checking username existence
FIRDatabase.database().reference().child("active_usernames").child(self.enteredUsername.text!).observeSingleEvent(of: .value, with: {(usernameSnap) in
if usernameSnap.exists(){
//This username already exists
}else{
//Yippee!.. This can be my username
}
})
Also change your security rules to be readable (ONLY READABLE) to all, by manipulating the security rules.
{rules :{
active_usernames : {
".read" : "true",
".write" : "auth != null"
}
}
}
PS:- enteredUsername
is the textField in which you enter your username.
Suggestion:- keep the checking code inside didChangeEditing
event of the textField(For better user experience.!)
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
}
}
}
}
Related Topics
Generic Swift 4 Enum With Void Associated Type
Reference to Property in Closure Requires Explicit 'Self.' to Make Capture Semantics Explicit
Pass Variables from One Viewcontroller to Another in Swift
Compile Error in Swift 4 on Parameter Passing
Programmatically Screenshot | Swift 3, Macos
Nsdateformatter Return Wrong Date + Swift
What Is the Reduce() Function Doing, in Swift
Reasons to Include Function in Protocol Definition VS. Only Defining It in the Extension
Firebase Email Verification at Signup
Uiapplication.Shared.Delegate Equivalent for Scenedelegate Xcode11
Override Func Error in Swift 2
How to Draw Text in PDF Context in Swift
Swift & Firebase | Checking If a User Exists with a Username
Swift: Decode Imprecise Decimal Correctly
What Causes 'Constant Captured by a Closure Before Being Initialized' Error