iosswifttableview

How to wait for an array to be filled in Swift


I am writing an app in Swift and having problems filling a tableview the right way. I am getting my data from Firestore and have a class to help me get that data. The basic process is that I have a getProducts function which sets a local array variable with products. The next step is to create an array of objects in my tableview class but my there seems to be a fault where my tableview gets build before my function has the time to load in the array. So my loadProducts fills the array products but my count seems to be 0.

Hope you can help.

My code:

class ProductTableViewController: UITableViewController {

    var products = [Product]()
    override func viewDidLoad() {
        super.viewDidLoad()
            loadProducts()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return products.count
    }
    
    private func loadProducts(){
        let dbhelper = DBHelper()
        dbhelper.getProducts(){ success in
            self.products = dbhelper.products
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "ProductTableViewCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ProductTableViewCell  else {
            fatalError("The dequeued cell is not an instance of ProductTableViewCell.")
        }
        
        let product = products[indexPath.row]
        cell.titleLabel.text = product.Titel
        cell.priceLabel.text = product.Prijs
        

        return cell
    }
}


Solution

  • Inside you load products func add a table view reload statment in order to reload the table with your new data :

    private func loadProducts(){
        let dbhelper = DBHelper()
        dbhelper.getProducts(){ success in
            self.products = dbhelper.products
            Self.tableView.reloadData()
        }
    }