gpt4 book ai didi

ios - Firebase - 获取对存储在 childByAutoID 下的值的引用

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:18 26 4
gpt4 key购买 nike

我一直在关注制作聊天应用程序的教程,该应用程序具有单独的“房间”,但它只是每个用户的一个中央列表 - 我正在尝试对其进行更改,以便每个用户都能看到自己房间的列表(他们创建的房间,以及他们被 friend 添加到的房间)。

这是处理创建房间并将其添加到列表的代码:

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

创建房间后,我想将新创建的房间添加到 Firebase 中用户的“房间”节点(我将尝试使用它来创建用户参与的房间列表),但是每个用户都有一个使用 childByAutoID 创建的唯一 ID,因此我不确定如何访问它。这就是我的 Firebase 数据库结构:

{
"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" : ""
}
}
}
}

如何正确地将房间添加到在 Firebase 中创建它的用户?

编辑:

试过了

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

它最终在“用户”下创建了第二个节点,而不是在该特定用户内。

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

最佳答案

你应该阅读 the documentation ,这是存储该 key 的方法:

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

关于ios - Firebase - 获取对存储在 childByAutoID 下的值的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com