Firebase - Retrieving a reference to the values โ€‹โ€‹stored in childByAutoID

I have been following a tutorial on how to create a chat application that has separate "rooms", but this is just one central list for each user - I am trying to change it so that each user can see a list of their rooms (the rooms they create and the rooms to which they are added by friends).

This is the code that handles the creation of the room and adds it to the list:

// Create new room
@IBAction func createRoom(_ sender: Any) {
    if let name = newRoomTextField?.text {
        let newRoomRef = roomRef.childByAutoId()
        let roomItem = [
            "name": name
        ]
        newRoomRef.setValue(roomItem)

        // How to add room to user room?
        let userRef: FIRDatabaseReference = FIRDatabase.database().reference().child("users")
    }
}

private func observeRooms() {
    // Observe method to listen for new channels being written to Firebase
    roomRefHandle = roomRef.observe(.childAdded, with: { (snapshot) -> Void in
        let roomData = snapshot.value as! Dictionary<String, AnyObject>
        let id = snapshot.key
        if let name = roomData["name"] as! String!, name.characters.count > 0 {
            self.rooms.append(Room(id: id, name: name))
            self.tableView.reloadData()
        } else {
            print("Error! Could not decode channel data")
        }
    })
}

      

When a room is created, I would like to add the newly created room to the custom "rooms" node in Firebase (which I will try to use to create a list of the users of the rooms they participate in), but each user has a unique ID created with childByAutoID

, so I don't sure how to access it. This is how my Firebase DB structure looks like:

{
  "rooms" : {
    "-KgK418WuJGjYw27Tg1-" : {
      "messages" : {
        "-KgK42e1zl3xxUS0E0C0" : {
          "senderId" : "2q4VCKu1e7hiL84ObdzgQcQ0pH63",
          "senderName" : "Timothy",
          "text" : "Hi"
        },
        "-KgK45LTf3R439mOMpvE" : {
          "senderId" : "2q4VCKu1e7hiL84ObdzgQcQ0pH63",
          "senderName" : "Timothy",
          "text" : "Testing"
        }
      },
      "name" : "Room One"
    }
  },
  "users" : {
    "-KgK3zXgap-iRFsbpv8D" : {
      "gender" : "male",
      "handle" : "TestHandle123",
      "name" : "Timothy",
      "profilePicture" : "https://graph.facebook.com/*removed for privacy*/picture?type=large&return_ssl_resources=1",
      "rooms" : {
        "roomName" : ""
      }
    }
   }
}

      

How can I correctly add a room to the user who created it in Firebase?

EDIT:

Tried this

        let userRef: FIRDatabaseReference = FIRDatabase.database().reference().child("users")
        let key = userRef.key
        let childUpdates = ["/\(key)/rooms/": roomItem]
        userRef.updateChildValues(childUpdates)

      

And that led to the creation of the second node under "users" rather than inside that particular user.

{
  "rooms" : {
    "-KgKS0VN65GS2r-Cz6K0" : {
      "name" : "Room Two"
    }
  },
  "users" : {
    "-KgKS-X63uSOMnpDWtDn" : {
      "gender" : "male",
      "handle" : "TestHandle123",
      "name" : "Timothy",
      "profilePicture" : "https://graph.facebook.com/*removed for privacy*/picture?type=large&return_ssl_resources=1"
        },
    "users" : {
         "rooms" : {
            "name" : "Room Two"
          }
        }
      }
    }

      

+3


source to share


1 answer


You should read the documentation , this is how you can store this key:



let key = ref.child("posts").childByAutoId().key

      

+4


source







All Articles