0

I'm trying to create a tableView within a viewController. I know it is annoying, but the table looks much better that way. I am also trying to incorporate data from Firebase to put into the table. Unfortunately when I run the code, it only shows a blank table. The console was able to print the desired data, but it just won't show on the actual table. Please let me know what I'm doing wrong. Many thanks!

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
 var user = Auth.auth().currentUser

var users = [Users]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self

    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

    tableView.reloadData()

    fetchUser()

}
func fetchUser() {
    Database.database().reference(fromURL: "https://yala-2018.firebaseio.com/").child("users").observe(.childAdded, with: { (DataSnapshot) in


        if let dictionary = DataSnapshot.value as? [String: AnyObject] {
            let user = Users()
           // user.setValuesForKeys(dictionary)

            user.name = dictionary["name"] as! String
            user.age = dictionary["age"] as! String
            user.sex = dictionary["sex"] as! String
            self.users.append(user)
            print(user.name, user.age)
            DispatchQueue.main.async(execute: {
            self.tableView.reloadData()
            })
        }


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

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

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCell(withIdentifier: "guide", for: indexPath)

    let user = users[indexPath.row]
    cell.textLabel?.text = user.name
    cell.detailTextLabel?.text = "Age: \(user.age) Sex: \(user.sex)"

 // Configure the cell...

 return cell
 }

func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
estelyk
  • 25
  • 9

1 Answers1

2

Change this to 1 as by 0 you mean no sections which will display empty tableView even if there is a data , or remove it as by default it's 1

func numberOfSections(in tableView: UITableView) -> Int {

   return 1
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Another problem, I am setting the prototype cell to 'subtitle'. I am able to get the textLabel to work, but not the detailTextLabel. Any idea why this is happening? I def set the cell style to subtitle in the IB. Thanks – estelyk May 14 '18 at 06:38