How to perform an action only after data are downloaded from Firebase

只谈情不闲聊 提交于 2019-11-28 14:43:22

Firebase is asynchronous so to make code execute in a defined order, you need to 'wait' for firebase to return data.

The closures that go with Firebase functions do just that - the code within the closure executes when the data (snapshot) is valid.

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

Note you can also remove this

if listOfTags.count != 0

as if listOfTags is 0, the for loop will not execute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!