Issues reading data from Firebase Database

前端 未结 1 483
无人共我
无人共我 2021-01-28 18:46

Okay I am reading from a database and when I print the individual variables they print out correctly. However it seems like the data refuses to append to the array. Anyone know

相关标签:
1条回答
  • 2021-01-28 19:23

    The data is correctly added to the array, just not at the time that you print the array's contents.

    If you change the code like this, you can see this:

    let commuteBuilder = Commutes()
    
    Database.database().reference().child("Users").child(user).child("Trips").observe(DataEventType.childAdded, with: { (snapshot) in
    
        if let dict = snapshot.value as? NSDictionary {
            commuteBuilder.distance = dict["Distance"] as! Double
            commuteBuilder.title = dict["TripName"] as! String
            commuteBuilder.transportType = (dict["Transport"] as? String)!
    
        }
    
        commuteArray.append(commuteBuilder)
        print("added one, now have \(commuteArray.count)")
    })
    print("returning \(commuteArray.count)")
    return commuteArray
    

    You'll see it print something like this:

    returning 0

    added one, now have 1

    added one, now have 2

    etc.

    This is likely not the output you expected. But it is working as intended. Firebase loads data from its database asynchronously. Instead of blocking your code, it lets the thread continue (so the user can continue using the app) and instead calls back to the code block you passed to observe when new data is available.

    This means that by the time this code returns the array it is still empty, but it later adds items as they come in. This means that you cannot return data from a function in the way you are trying.

    I find it easiest to change my way of thinking about code. Instead of "First get the data, then print it", I frame it as "Start getting the data. When data comes back, print it".

    In the code above, I did this by moving the code that prints the count into the callback block. Instead of doing this, you can also create your own callback, which is called a completion handler or closure in Swift. You can find examples in this article, this article, this question Callback function syntax in Swift or of course in Apple's documentation.

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