Swift 5,如何从Firebase提取所有子代后执行代码 [英] Swift 5, how to execute code after fetching all childadded from Firebase

查看:53
本文介绍了Swift 5,如何从Firebase提取所有子代后执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 5中从Firebase提取所有增添的子代后,如何执行一些代码?

How can I execute some code after fetching all childadded from Firebase in Swift 5?

我尝试使用DispatchGroup并观察.value,但是它们都无法有效地工作.

I've tried using DispatchGroup and observe .value, but none of them worked efficiently.

let dispatchGroup = DispachGroup()

ref.child("path").observe(.childAdded, with: { (snapshot) in
     self.dispatchGroup.enter()
     //store snapshot data into an object
     self.dispatchGroup.leave()
})

dispatchGroup.notify(queue: .main) {
    //code to execute after all children are fetched
}

在这种情况下,将在获取数据之前执行代码.

In this case, the code will be executed before fetching the data.

当只有回调块到达最后一个孩子时,我如何执行代码?

How can I execute code when only the callback block reaches the last child?

推荐答案

一种选择是利用Firebase .value函数在.childAdded函数之后调用.

One option is to leverage that Firebase .value functions are called after .childAdded functions.

这意味着.childAdded将遍历所有childNode,然后在读取最后一个childNode之后,将调用任何.value函数.

What this means is that .childAdded will iterate over all childNodes and then after the last childNode is read, any .value functions will be called.

假设我们要遍历一个用户节点中的所有用户,打印他们的名字,并且在打印出最后一个用户名之后,输出一条消息,表明已读入所有用户.

Suppose we want to iterate over all users in a users node, print their name and after the last user name is printed, output a message that all users were read in.

从简单的结构开始

users
   uid_0
      name: "Jim"
   uid_1
      name: "Spock"
   uid_2
      name: "Bones"

然后是一次读取用户的代码,打印出他们的名字,然后在读取完所有名字后输出到控制台

and then the code that reads the users in, one at a time, prints their name and then outputs to console when all names have been read

var initialRead = true

func readTheUsers() {
    let usersRef = self.ref.child("users")

    usersRef.observe(.childAdded, with: { snapshot in
        let userName = snapshot.childSnapshot(forPath: "name").value as? String ?? "no name"
        print(userName)

        if self.initialRead == false {
            print("a new user was added")
        }
    })

    usersRef.observeSingleEvent(of: .value, with: { snapshot in
        print("--inital load has completed and the last user was read--")
        self.initialRead = false
    })
}

和输出

Jim
Spock
Bones
--inital load has completed and the last user was read--

请注意,这会将观察者留在用户节点上,因此,如果添加了新用户,它也会打印其名称.

Note this will leave an observer on the users node so if a new user is added it will print their name as well.

注意注意:self.ref指向我的根Firebase参考.

Note Note: self.ref points to my root firebase reference.

这篇关于Swift 5,如何从Firebase提取所有子代后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆