1

我剛剛將Facebook登錄功能集成到我的Firebase應用程序中。我想在FIRDatabase中向用戶添加一些額外的信息。這就是爲什麼我添加一個孩子用戶的uid作爲我的firebase數據庫的標識符。如何將Facebook用戶的uid存儲在Firebase中?

當用戶使用「正常」註冊功能(沒有臉書)時,一切都像黃油一樣平穩。然而,現在我向Facebook註冊表中添加了相同的信息,它給出了這個致命錯誤,當swift發現意外的時候發生了意外的錯誤,同時展開一個可選值。

我知道它必須是我添加到FIRDatabase的uid。但我還沒有想出如何在其他地方使用uid。

var FirebaseUId: String! 
func showEmailAddress() { 
    let accessToken = FBSDKAccessToken.current() 
    guard let accessTokenString = accessToken?.tokenString else {return} 

    let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString) 

    FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in 
     if error != nil { 
      print("Something went wrong with our FB user:", error ?? "") 
      return 
     } 
     print("succesfullex logged in with our user: ", user ?? "") 
     self.FirebaseUId = user?.uid 
    }) 
    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, err) in 
     if err != nil { 

      return 

     } 
     print(result ?? "") 
     let data = result as! [String : AnyObject] 
     let email = data["email"] as? String 
     let username = data["name"] as? String 

     let userInfo: [String : Any] = ["uid" : self.FirebaseUId! , 
             "username" : username!, 
             "Email" : email!, 
             "Passwort" : " ", 
             "Geschlecht" : " ", 
             "urltoImage" : " ", 
             "FußballPreferenz" : " ", 
             "BasketballPreferenz" : " ", 
             "FußballBesitz" : " ", 
             "BasketballBesitz" : " ", 
             "LeibchenBesitz" : " "] 
     var ref: FIRDatabaseReference! 
     ref = FIRDatabase.database().reference() 

     ref.child("users").child(self.FirebaseUId).setValue(userInfo) 

    } 


} 

回答

0

這就是我如何完成你所要做的。

//this is what we need to save to FB 
    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { //this gets info 
     (connection, result, err) in 

     if err != nil { 
      print("graph failed", err as Any) 
      return 
     } 

    Auth.auth().signIn(with: credential, completion: { (user, error) in //this logs you in 
     if error != nil { 
      print("something wrong", error as Any) 
      return 
     } 
     let uid = user?.uid 

     let ref = Database.database().reference()    //below adds the info to the db 
     let usersRef = ref.child("users").child(uid!) 

     usersRef.updateChildValues(result as! [AnyHashable : Any]) 

     print("userID", uid as Any) 
     }) 

    } 

您需要包裹簽到圖請求裏面,所以你可以拉從標誌UID,以及獲得來自graphrequest的信息。這也將允許您使用其他登錄方法,例如Google,並仍然提取正確的uid。

相關問題