Home>

My name is Ryoma. I'm making a matching app.
I have a question about FIrebase.
After randomly generating id with childByAutoId, I would like to store (add) the data of that user under it.
As shown in the attached figure below, the data itself is stored in the DB, but a different id is generated each time and stored under it.

] (ba45bf1fd6a8144dd8a59f411cc8e886.png)/p>

Tell me how I can get the same Id and store the data under the same Id!
I will put the code I wrote at the end. Thanks for your patience.

Applicable source code

Get information at facebook login, code stored in firebase

facebookLogin.swift

func postUser () {
    guard let user = Auth.auth (). currentUser else {
        assert (true, "post user with nil")
        return
    }
    let facebookId = FBSDKAccessToken.current (). userID
    let userRef = ref.child ("Users")
    userRef
        .queryOrdered (byChild: "facebookId")
        .queryEqual (toValue: facebookId)
        .observeSingleEvent (of: DataEventType.value) {(snapshot) in
            if snapshot.exists () {
                print ("Exist user")
            } else {

                let postUser = ["facebookId": FBSDKAccessToken.current (). userID,
                                "name": user.displayName]
                let postUserRef = userRef.childByAutoId ()
                postUserRef.setValue (postUser)
            }
    }


File code for editing user information
myPageUpdata.swift (I want to store to the same user table when storing to firebase here)

// Fires when the finish button is pressed. Save data to firebase.
    @IBAction func completeButton (_ sender: Any) {
        let user = Auth.auth (). currentUser
        // updateChildValues ​​update Save key if key is not included. Setvalue to update only the value (setValue overwrites everything below the specified hierarchy)
        ref.child ("Users"). child ((user? .uid)!). updateChildValues ​​(["Occupation": workPlaces.text])
        ref.child ("Users"). child ((user? .uid)!). updateChildValues ​​(["Education": education.text])
        ref.child ("Users"). child ((user? .uid)!). updateChildValues ​​(["Gender": selectGender])
    }
  • Answer # 1

    You can use uid obtained from Auth without using childByAutoId.

    let postUser = ...
    let postUserRef = userRef.child (user.uid)
    postUserRef.updateChildValues ​​(postUser)

    It is a digression, but if you write in myPageUpdata.swift together, it is better to reduce the number of writes to DB.

    ref.child ("Users"). child ((user? .uid)!). updateChildValues ​​([
        "Occupation": workPlaces.text,
        "Education": education.text,
        "Gender": selectGender
    ])