Swift/Firebase:当他们创建帐户时,如何正确地将Facebook用户存储到Firebase数据库中? [英] Swift / Firebase: How do I properly store a Facebook user into Firebase database when they create an account?

查看:58
本文介绍了Swift/Firebase:当他们创建帐户时,如何正确地将Facebook用户存储到Firebase数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户保存到我的Firebase数据库中.我正在使用FBSDKLoginManager()创建帐户/登录.创建帐户后,我想将用户存储到我的Firebase数据库中.我目前可以登录用户,并且他们的电子邮件显示在firebase的身份验证"标签中(请参见屏幕截图),但是我的updateChildValues似乎没有任何影响(请参见屏幕截图).

I'm trying to save users to my firebase database. I'm using a FBSDKLoginManager() to create an account / log in. Upon account creation, I want to store the users into my firebase database. I can currently log the user in and their email shows up in the Auth tab of firebase (see screenshot), but my updateChildValues doesn't seem to be having any affect (also see screenshot).

我将updateChildValues放在正确的位置吗?当前位于signInWithCredential中.我还必须执行FBSDKGraphRequest以获得我感兴趣的信息存储在我的Firebase数据库中.

Am I placing the updateChildValues in the right place? It's currently place within signInWithCredential. I also have to perform an FBSDKGraphRequest to get the info I'm interested in storing in my firebase database.

我的Firebase的身份验证"标签显示身份验证正在工作:

但是数据库未更新:

    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's 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")
                })
            }
        }
    })
}

更新:

很显然,大约10分钟后,该数据库已使用空白的Facebook数据进行了更新...不知道为什么要花这么长时间.这是屏幕截图:

Apparently after 10 minutes or so, the database was updated with empty Facebook data... Not sure why it's taking so long. Here's a screenshot:

推荐答案

您仅应在执行完成块graphRequest.startWithCompletionHandler时更新值,因为这是从Facebook上获取数据的时间! usersReference.updateChildValues必须位于完成块的graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in内部.我在下面附上了它.试试吧!

You should only update the values when the completion block graphRequest.startWithCompletionHandler is executed because that's when you will get your data from the Facebook!. usersReference.updateChildValues needs to be inside graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in the completion block. I have attached it below. Try it!!

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's 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")
                        })
                    }
                })


            }
        }
    })
}

这篇关于Swift/Firebase:当他们创建帐户时,如何正确地将Facebook用户存储到Firebase数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆