我的 firebase 数据库结构如下:
events
autoid
event name: ""
event date: ""
autoid
event name: ""
event date: ""
我目前有一个函数可以从事件节点返回所有 autoid,然后将它们写入一个数组,这样我就可以在另一个快照中使用它们。
函数第一次运行时,它按预期工作。但如果我离开 View 再回来,它就会崩溃。我认为这是因为它试图再次附加数组,复制值。
这是我的功能
func getEvents() {
self.dispatchGroup.enter()
Database.database().reference().child("Events").observe(DataEventType.value, with: { (snapshot) in
if let dictionary = snapshot.children.allObjects as? [DataSnapshot] {
// self.dispatchGroup.enter()
for child in dictionary {
let eventid = child.key
self.eventsArray.append(eventid)
// print(eventid)
// print(self.eventsArray)
}
self.dispatchGroup.leave()
print(self.eventsArray)
}
})
}
想知道当我返回 View 时如何检索现有的 autoid 和任何已添加的新 autoid。我试过 .childadded 但它返回事件名称、事件日期等,我需要 autoid。
我是 firebase 和 swift 的新手,所以欢迎任何提示或建议!
最佳答案
如果您想先处理初始数据,然后只收到有关新数据的通知,您通常会寻找 .childAdded
事件。
Database.database().reference().child("Events").observe(DataEventType.childAdded, with: { (snapshot) in
let eventid = snapshot.key
print(eventid)
self.eventsArray.append(eventid)
self.dispatchGroup.leave()
print(self.eventsArray)
}
当您第一次运行这段代码时,.childAdded
事件会为每个现有的子节点触发。之后,每当添加新的 child 时它都会触发。同样,您可以监听 .childChanged
和 .childRemoved
事件来处理这些事件。
关于swift - 自从我上次使用 swift 从 firebase 调用函数以来,如何只检索 autoids。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837716/