Frederic
Frederic

Reputation: 497

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
}    

}

Upvotes: 1

Views: 684

Answers (1)

Nirav D
Nirav D

Reputation: 72410

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()
})

Upvotes: 1

Related Questions