user8991296
user8991296

Reputation:

Swift Tableview not loading data

I'm learning to develop iOS app and on my first app, I have a tableView that should display the data from FirebaseDatabase.

Below is the database structure:

enter image description here

Below is the code from viewcontroler.swift

import UIKit
import Firebase

class ctrTableViewController: UITableViewController {

    var _ctrsArray = [String]()

    var dbref = Database.database().reference()

    let deviceID = UIDevice.init().identifierForVendor

    func loadCtrs() {
        // Load ctrs from DB to Tableview

        dbref.child("\(String(describing: deviceID))/ctrs").observeSingleEvent(of: .value, with: { snapshot in
            if let ctrs = snapshot.value as? [String: Any] {
                for (ctr, _) in ctrs {
                    self._ctrsArray.append(ctr)
                    self.tableView.reloadData()
                }
            }
        })
    }

    override func viewDidLoad() {

        super.viewDidLoad()
        loadCtrs()

         self.navigationItem.leftBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return _ctrsArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ctrCell")
        cell?.textLabel?.text = _ctrsArray[indexPath.row]
        return cell!
    }

}

What am I missing? TIA for all your help.

Upvotes: 0

Views: 80

Answers (2)

Juri Noga
Juri Noga

Reputation: 4391

To prevent crashing you have to register you cell for reuse, for example in viewDidLoad (before loadCtrs) in case you're using nibs add:

tableView.register(UINib(nibName: <#nibName#>, bundle: nil), forCellReuseIdentifier: "ctrCell")

And in case you're not using nibs for your custom cells:

tableView.register(<#CustomClass#>.self, forCellReuseIdentifier: "ctrCell")

Upvotes: 0

Chris
Chris

Reputation: 275

You set numberOfSections to 0, so there can't be displayed any data. If you want only 1 Section set it to 1, or remove the method. It is set to 1 by default.

Upvotes: 1

Related Questions