Frederic Frederic - 2 months ago 10
iOS Question

Retrieving data from Firebase to tableview

In a view, my user types some text in a input field, which I save as a

ticket
(this process works without problems and are added to my database successfully).

I want all these
ticket
values to be presented in a
tableView
in which each cell contains a
ticket
. I've been playing around, and this is as far as I could go, but it is still not enough.

import UIKit
import Firebase

class TestTableViewController: UITableViewController {

let cellNavn = "cellNavn"

var holes: [FIRDataSnapshot]! = []


let CoursesRef = FIRDatabase.database().reference().child("Ticketcontainer")


override func viewDidLoad() {
super.viewDidLoad()

CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
self.holes = snapshot.childSnapshotForPath("tickets").children.allObjects as! [FIRDataSnapshot]
})

navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(handleCancel))

tableView.registerClass(UserCell.self, forCellReuseIdentifier: cellNavn)


}


func handleCancel() {
dismissViewControllerAnimated(true, completion: nil)
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellNavn, forIndexPath: indexPath) as! UserCell
cell.textLabel?.text = self.holes[indexPath.row].value as? String

return cell

}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72
}

}

Answer

First of all in numberOfRowsInSection method you need to return your array's count instead of some static value.

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return holes.count
}

Second after initializng your array in closure you need to reload the tableView.

CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
    self.holes = snapshot.childSnapshotForPath("tickets").children.allObjects as! [FIRDataSnapshot]
    self.tableView.reloadData()
})
Comments