DCDC DCDC - 3 months ago 21
Swift Question

How to save to Firebase - Swift

Probably I get something wrong.

This is how I try to store user data after fb auth:

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError?) {
print("sds")
print(result)
if let error = error {
print(error.localizedDescription)
return
}
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)

FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in

if let email = user?.email
{
self.ref.child("users").child(user!.uid).setValue(["email": email])
}
if let photoURL = user?.photoURL?.absoluteString
{
self.ref.child("users").child(user!.uid).setValue(["photoURL": photoURL])
}
}}


What I get when I look into database in console is only the photoURL, looks like email is created and immmediately after deleted/overriden.

What's the correct way to save data to firebase?

Answer

When you set value you are overwriting everything at that path.

If you only want to replace certain values you should use:

self.ref.child("users").child(user!.uid).child("photoURL").setValue(photoURL)

Or replace/create entire user object

self.ref.child("users").child(user!.uid).setValue(["email": email, "photoURL": user?.photoURL?.absoluteString ?? ""])