当前位置: 首页 > 知识库问答 >
问题:

Swift/Firebase:如何在Facebook用户创建帐户时将其正确存储到Firebase数据库中?

公良琛
2023-03-14

我正在尝试将用户保存到我的Firebase数据库。我正在使用FBSDKLoginManager()创建帐户/登录。创建帐户后,我想将用户存储到我的Firebase数据库中。我目前可以登录用户,他们的电子邮件显示在Firebase的Auth选项卡中(见屏幕截图),但我的updateChildValures似乎没有任何影响(另见屏幕截图)。

我是否将updatechildvalue放在了正确的位置?它当前位于带有凭据的登录中。我还必须执行FBSDKGraphRequest以获取我感兴趣的信息,并将其存储在我的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数据。。。不知道为什么要花这么长时间。以下是屏幕截图:

共有2个答案

子车煌
2023-03-14

您应该只在执行完成块时更新值graph Request.startNevCompletionHandler,因为那是您从Facebook获取数据的时候!。usersReference.updateChildValures需要在graph R内部equest.startSusCompletionHandler({(连接、结果、错误)-

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


            }
        }
    })
}

邵飞白
2023-03-14

Swift 3:(只在末尾更改,节省了很多行)

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


                }
            }
        })
    }
 类似资料:
  • 我想问如何创建两个单独的登录意图。例如,一个是给客户的,一个是给管理员检查细节的。 在这段代码中,它只能显示客户部分,但我如何输入另一种方式,在那里有单独的管理或管理和客户的使用? 更新的一个

  • 我试图实现一个功能来删除当前用户的帐户上iOS。帐户删除工作正常,但问题是删除帐户时,我无法从数据库和存储中删除帐户的数据。 “currentUser.delete”删除该帐户,但我认为没有身份验证可以从数据库和存储中删除其数据。日志中将显示“权限被拒绝”消息。运行此功能后,我看到Firebase控制台验证页面中的帐户已消失,但来自数据库和存储的数据仍然存在。 这是删除帐户的正确方法吗? 在删除帐

  • 我正在尝试构建一个只有当前用户才能为新用户创建帐户的应用程序。我有两种用户医生和病人。只有医生才能为患者创建账户。到目前为止,Iv创建了一个Firebase数据库,它似乎正在工作,但现在已经停止。患者目前正在接受身份验证,但他们的信息没有被添加到数据库中。我认为问题在于在当前用户登录时尝试创建新用户。是否允许用户创建一个新用户,而无需作为新创建的用户登录? 此代码创建患者帐户并将其添加到Fireb

  • 我有一个场景,我通过使用firebase身份验证通过匿名登录,并从匿名登录帐户,我已经从事件列表中添加了事件作为收藏夹项目,现在我想使用Google或Facebook登录,以便我最喜欢的项目永远不会丢失,每当我登录收藏夹项目必须从该登录帐户获得。 我正在使用上述场景Firebase链接。但问题是,firebase链接只对一个匿名帐户有效一次,如果我再次匿名登录并添加最喜欢的事件,现在我使用以前的方

  • 所以我试图将一些数据存储到我的实时数据库中。我目前有两个独立的视图控制器,一个用于用户注册,另一个用于用户选择其配置文件图像并能够更改该图像。在注册页面上,我将“用户名”保存到firebase,如下所示: 对于个人资料图像,我有这样保存的数据 我希望这两个数据都保存在“用户”下-

  • 告诉我如何在Azure存储帐户中存储PostgreSQL数据库数据。PostgreSQL部署到Azure容器实例。当我重新启动Azure容器实例时,所有数据都会消失。Dockerfile 来自Timescale/Timescaledb:Latest-PG12 az容器创建--resource-group test-env--name test-env--image test-env.azureca