swift - 自从我上次使用 swift 从 firebase 调用函数以来,如何只检索 autoids。

标签 swift firebase firebase-realtime-database

我的 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/

相关文章:

swift - 枚举变量的模式翻转

Firebase Analytics 事件 - currentScreen 始终为 screen_view

android - 从 Firebase 获取通知历史记录

swift - 单击 TableViewCell 打开当前用户的个人资料 View

ios - 如何增加 inputAccessoryView 的高度

ios - 如何将 4 个 uibutton 居中,彼此之间的距离相等?

java - Firebase 如何在 Android 中打开其他 Activity 时删除 ValueEventListener

android - Firebase——错误 : Program type already present: com. google.api.AuthProviderOrBuilder

javascript - 使用两个之间条件查询 Firebase 数据库

ios - Swift解压缩zip文件并从Gmail API的base64数据中查找xml文件