Swift / Firebase: how to properly store a Facebook user in a Firebase database when creating an account?

I am trying to save users in a firebase database. I use FBSDKLoginManager()to create an account / login. After creating the account, I want to save users to my firebase database. Now I can enter into the system and their e-mail appears on the Auth firebase tab (see. Screenshot), but mine updateChildValuesdid not seem to affect (see. Also a screenshot).

Am I putting updateChildValuesin the right place? It is currently within signInWithCredential. I also have to execute FBSDKGraphRequestto get the information that I am interested in storing in my firebase database.

My firebase's Auth tab shows how authentication works: enter image description here

But the database is not updated: enter image description here

    func showLoginView() {
    let loginManager = FBSDKLoginManager()
    loginManager.logInWithReadPermissions(fbPermissions, fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in

        if ((error) != nil) {
            print("Error loggin in is \(error)")
        } else if (result.isCancelled) {
            print("The user cancelled loggin in")
        } else {
            // No error, No cancelling:
            // using the FBAccessToken, we get a Firebase token
            let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)

            // using the credentials above, sign in to firebase to create a user session
            FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
                print("User logged in the firebase")

                // adding a reference to our firebase database
                let ref = FIRDatabase.database().referenceFromURL("https://project-12345.firebaseio.com/")

                // guard for user id
                guard let uid = user?.uid else {
                    return
                }

                // create a child reference - uid will let us wrap each users data in a unique user id for later reference
                let usersReference = ref.child("users").child(uid)

                // performing the Facebook graph request to get the user data that just logged in so we can assign this stuff to our Firebase database:
                let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
                graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

                    if ((error) != nil) {
                        // Process error
                        print("Error: \(error)")
                    } else {
                        print("fetched user: \(result)")

                        // Facebook users name:
                        let userName:NSString = result.valueForKey("name") as! NSString
                        self.usersName = userName
                        print("User Name is: \(userName)")
                        print("self.usersName is \(self.usersName)")

                        // Facebook users email:
                        let userEmail:NSString = result.valueForKey("email") as! NSString
                        self.usersEmail = userEmail
                        print("User Email is: \(userEmail)")
                        print("self.usersEmail is \(self.usersEmail)")

                        // Facebook users ID:
                        let userID:NSString = result.valueForKey("id") as! NSString
                        self.usersFacebookID = userID
                        print("Users Facebook ID is: \(userID)")
                        print("self.usersFacebookID is \(self.usersFacebookID)")
                    }
                })

                // set values for assignment in our Firebase database
                let values = ["name": self.usersName, "email": self.usersEmail, "facebookID": self.usersFacebookID]

                // update our databse by using the child database reference above called usersReference
                usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                    // if there an error in saving to our firebase database
                    if err != nil {
                        print(err)
                        return
                    }
                    // no error, so it means we've saved the user into our firebase database successfully
                    print("Save the user successfully into Firebase database")
                })
            }
        }
    })
}

Update:

Apparently, after 10 minutes or so, the database was updated with empty data on Facebook ... I don’t know why it took so long. Here is a screenshot:

enter image description here

+5
source share
2 answers

You should only update the values ​​when the completion block is executed graphRequest.startWithCompletionHandler, because when you will receive your data from Facebook !. usersReference.updateChildValuesmust be inside graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void inthe completion block. I attached it below. Give it a try!

func showLoginView() {
    let loginManager = FBSDKLoginManager()
    loginManager.logInWithReadPermissions(fbPermissions, fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in

        if ((error) != nil) {
            print("Error loggin in is \(error)")
        } else if (result.isCancelled) {
            print("The user cancelled loggin in")
        } else {
            // No error, No cancelling:
            // using the FBAccessToken, we get a Firebase token
            let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)

            // using the credentials above, sign in to firebase to create a user session
            FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
                print("User logged in the firebase")

                // adding a reference to our firebase database
                let ref = FIRDatabase.database().referenceFromURL("https://project-12345.firebaseio.com/")

                // guard for user id
                guard let uid = user?.uid else {
                    return
                }

                // create a child reference - uid will let us wrap each users data in a unique user id for later reference
                let usersReference = ref.child("users").child(uid)

                // performing the Facebook graph request to get the user data that just logged in so we can assign this stuff to our Firebase database:
                let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
                graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

                    if ((error) != nil) {
                        // Process error
                        print("Error: \(error)")
                    } else {
                        print("fetched user: \(result)")

                        // Facebook users name:
                        let userName:NSString = result.valueForKey("name") as! NSString
                        self.usersName = userName
                        print("User Name is: \(userName)")
                        print("self.usersName is \(self.usersName)")

                        // Facebook users email:
                        let userEmail:NSString = result.valueForKey("email") as! NSString
                        self.usersEmail = userEmail
                        print("User Email is: \(userEmail)")
                        print("self.usersEmail is \(self.usersEmail)")

                        // Facebook users ID:
                        let userID:NSString = result.valueForKey("id") as! NSString
                        self.usersFacebookID = userID
                        print("Users Facebook ID is: \(userID)")
                        print("self.usersFacebookID is \(self.usersFacebookID)")

                        //graphRequest.startWithCompletionHandler may not come back during serial
                        //execution so you cannot assume that you will have date by the time it gets
                        //to the let values = ["name":
                        //By putting it inside here it makes sure to update the date once it is
                        //returned from the completionHandler
                        // set values for assignment in our Firebase database
                        let values = ["name": self.usersName, "email": self.usersEmail, "facebookID": self.usersFacebookID]

                        // update our databse by using the child database reference above called usersReference
                        usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                            // if there an error in saving to our firebase database
                            if err != nil {
                                print(err)
                                return
                            }
                            // no error, so it means we've saved the user into our firebase database successfully
                            print("Save the user successfully into Firebase database")
                        })
                    }
                })


            }
        }
    })
}
+3
source

Swift 3: (only changed it at the end, saves a lot of lines)

 func showLoginView() {
        let loginManager = FBSDKLoginManager()
        loginManager.logInWithReadPermissions(fbPermissions, fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in

            if ((error) != nil) {
                print("Error loggin in is \(error)")
            } else if (result.isCancelled) {
                print("The user cancelled loggin in")
            } else {
                // No error, No cancelling:
                // using the FBAccessToken, we get a Firebase token
                let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)

                // using the credentials above, sign in to firebase to create a user session
                FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
                    print("User logged in the firebase")

                    // adding a reference to our firebase database
                    let ref = FIRDatabase.database().referenceFromURL("https://project-12345.firebaseio.com/")

                    // guard for user id
                    guard let uid = user?.uid else {
                        return
                    }

                    // create a child reference - uid will let us wrap each users data in a unique user id for later reference
                    let usersReference = ref.child("users").child(uid)

                    // performing the Facebook graph request to get the user data that just logged in so we can assign this stuff to our Firebase database:
                    let graphRequest : FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, email, name"]).start{
                        (connection, result, err) in

                        if ((error) != nil) {
                            // Process error
                            print("Error: \(error)")
                        } else {
                            print("fetched user: \(result)")

                            let values: [String:AnyObject] = result as! [String : AnyObject]

                            // update our databse by using the child database reference above called usersReference
                            usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                                // if there an error in saving to our firebase database
                                if err != nil {
                                    print(err)
                                    return
                                }
                                // no error, so it means we've saved the user into our firebase database successfully
                                print("Save the user successfully into Firebase database")
                            })
                        }
                    })


                }
            }
        })
    }
+4

Source: https://habr.com/ru/post/1654239/


All Articles