I'm using Firebase in my Swift / iOS project, and am trying to implement a check to determine whether or not a user exists already in the database when they're in the sign - in / login user flow.
This is what I'm currently using as a check of whether the user exists...no matter what, even if I can visually verify that the user is in my database, I always get a result of the user not existing.
if let user = Auth.auth().currentUser {
let ref = self.ref.child("users").child(user.uid)
ref.observeSingleEvent(of: .value, with: { snapshot in
self.performSegue(withIdentifier: "GoToMainViewController", sender: nil)
})
} else {
self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
}
I've tried the accepted in these two SO threads here and here, but am consistently getting the same result.
EDIT: This is my database structure
EDIT2: This is the full flow, including the code where I've authenticated the signed in user (via phone number). At both places where I'm logging the the user ID, I get that of the logged-in ID.
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
let alert = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { actions in
})
self.present(alert, animated: true)
return
}
let userID = Auth.auth().currentUser?.uid
print(userID)
Auth.auth().addStateDidChangeListener { auth, user in
if user != nil{
print("user is not nil")
//self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: self)
}
else{
print("user is nil")
//self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
}
}
print(userID)
//Check if user exists
if let user = Auth.auth().currentUser {
let ref = self.ref.child("users").child(user.uid)
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
//self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: nil)
})
} else {
//self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
}
This is what the resultant snapshot looks like:
Snap (sxQLr6p9meZyQi8p8RPrjVxcUi33) {
bio = h;
birthday = "11-Feb-1989";
firstname = n;
lastname = n;
}