Finish asynchronous task in Firebase with Swift

后端 未结 2 1592
闹比i
闹比i 2020-12-07 00:30

I am trying to write a function that will return an array of all my workers, but it is returning before retrieving the data from firebase

here is my code:

2条回答
  •  遥遥无期
    2020-12-07 01:03

    The code in your question doesn't work due to a fundamental issue: Firebase is asynchronous and can't be called to return values like a function.

    Firebase data is only viable when (within) the block that fetched it has completed.

    App code runs much faster than the internet, so if you tell Firebase to fetch data and then try to work with that data outside the block (with return workerList for example) the return will fire way before the Firebase data is ready, and you'll return nil sometimes, maybe always.

    So what do you do? You code in an asynchronous way.

    Say for example, you have a tableView that presents a list of workers. Here's a conceptual flow

    tell firebase to get data withBlock {
        iterate over returned snapshot data to populate an array
        when done, tableView.reloadData
    }
    

    The key is to leverage the asynchronous nature of Firebase and write code that works with Firebase.

提交回复
热议问题