self.tableView.reloadData not working when trying to read and get back data from a firebase realtime database

20 views Asked by At

I am trying to reload data from a firebase realtime database (xcode 15.2).

I used self.tableView.reloadData() to obtain the data in my variable but it does not work.

In the debugger my 2 print give me: But there, the result is []

Here the result is : [EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message"))] Here the result is : [EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message")), EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message"))] Here the result is : [EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message")), EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message")), EasyFoodDiary.postStruct(title: Optional("Title"), message: Optional("Message"))]

I would expect the same.

Here is my code:

import UIKit
import Firebase
import FirebaseDatabase

struct postStruct {
    let title : String!
    let message : String!
}

class FoodDiaryTableViewController: UITableViewController {

    var posts = [postStruct]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        
        let databaseRef = Database.database().reference()
        
        databaseRef.child("Posts").queryOrderedByKey().observe(.childAdded, with: {
            snapshot in
            
            let value = snapshot.value as? NSDictionary
            let title = value?["title"] as? String ?? ""
            let message = value?["message"] as? String ?? ""
            
            self.posts.insert(postStruct(title: title, message: message), at: 0)
            
            DispatchQueue.main.async{
                self.tableView.reloadData()
            }
            print("Here the result is : \(self.posts)")
        })
        
        print("But there, the result is \(self.posts)")
    }
            

And hre is my database:

Hi would expect the data to be reloaded down and therefore have the same result for the 2 prints.

I want to get back the datas from the database in my code.

0

There are 0 answers