如何仅在从 Firebase 下载数据后执行操作 [英] How to perform an action only after data are downloaded from Firebase
问题描述
我想弄清楚如何仅在 Firebase 中的 observeSingleEvent 完成其工作后才触发操作.
I'm trying to figure out how to trigger an action only after the observeSingleEvent in Firebase has finished its work.
背后的原因是我需要做如下操作:
The reason behind is that I need to do the following operations:
- 根据用户的一项输入,我需要从数据库中获取一些数据
- 当这些数据完全下载后,我需要对它们进行一点处理,并用于检索其他数据以显示给用户
目前我正在使用此代码:
Currently I'm using this code:
let listOfTags = [String]()
var outputArray = [String]()
if listOfTags.count != 0 {
for tag in listOfTags {
ref.child("tags").child(tag).observeSingleEvent(of: .value, with: { (snapshot) in
if let temp = snapshot.children.allObjects as? [FIRDataSnapshot] {
for elem in temp {
outputArray.append(elem.key)
}
}
// ...
}) { (error) in
print(error.localizedDescription)
}
}
// HERE I WANT TO DO AN ACTION "ONLY" AFTER THE FOR LOOP IS
// COMPLETED AND THE "outputArray" IS FILLED WITH ALL VALUES
doSomethingHere()
}
但我注意到函数 doSomethingHere() 在 outputArray 仍然是 EMPTY 时立即执行!所以它什么都不做.
But I noticed that the function doSomethingHere() is executed immediately when the outputArray is still EMPTY! So it does nothing.
那么我的问题是,如何构建程序,以便在下载过程完成后执行此功能?也许observeSingleEvent 不是要使用的正确Firebase 方法?对于这种特定情况,我不想观察任何更改(因为此列表不会经常更改),我只需要下载数据并稍后对这些数据执行其他操作..
Then my question is, how can I structure the program such that this function is executed after the downloading process is completed? Maybe observeSingleEvent is not the correct Firebase method to be used? For this specific case I don't want to observe any change (because this list is not changing so often), I just need to download data and do something else with these data later ..
推荐答案
Firebase 是异步的,所以要让代码按照定义的顺序执行,你需要等待"firebase 返回数据.
Firebase is asynchronous so to make code execute in a defined order, you need to 'wait' for firebase to return data.
与 Firebase 函数一起使用的闭包就是这样做的 - 当数据(快照)有效时,闭包中的代码就会执行.
The closures that go with Firebase functions do just that - the code within the closure executes when the data (snapshot) is valid.
将 doSomethingHere() 移到 Firebase 闭包中,它将以正确的顺序执行 - 在这种情况下
Move doSomethingHere() to within the Firebase closure and it will execute in the correct order - in this case
if listOfTags.count != 0 {
for tag in listOfTags {
ref.child("tags").child(tag).observeSingleEvent(of: .value, with: { (snapshot) in
if let temp = snapshot.children.allObjects as? [FIRDataSnapshot] {
for elem in temp {
outputArray.append(elem.key)
}
doSomethingHere() //array is populated at this point
}
})
}
}
注意你也可以删除这个
if listOfTags.count != 0
当 listOfTags 为 0 时,for 循环将不会执行.
as if listOfTags is 0, the for loop will not execute.
这篇关于如何仅在从 Firebase 下载数据后执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!