KingTim
KingTim

Reputation: 1301

Firebase - Getting a reference to values stored under childByAutoID

I've been following a tutorial on making a chat app, which has separate "rooms", but it's just one central list for every user - I'm trying to alter it so each user sees a list of their own rooms (rooms that they create, and rooms they are added to by friends).

This is the code that handles creating a room and adding 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's 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'd like to add the newly created room to the user's "rooms" node in Firebase (which I'll try to use to create the user's list of rooms that they participate in), but each user has a unique ID created with childByAutoID, so I'm not sure how to access it. This is what 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 properly add the 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 it ended up making a second node under "users", instead of within 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"
          }
        }
      }
    }

Upvotes: 4

Views: 961

Answers (1)

Damien
Damien

Reputation: 3362

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

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

Upvotes: 6

Related Questions