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

后端 未结 1 974
一个人的身影
一个人的身影 2020-12-12 07:50

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 fo

1条回答
  •  离开以前
    2020-12-12 08:25

    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.

    0 讨论(0)
提交回复
热议问题