MooseMan55 MooseMan55 - 1 month ago 4
Swift Question

Why won't my UITableViewCells show information?

When I start my app it should show the name and location data of all the parties in my database but it doesn't. I'm pretty sure I'm getting the right data but i don't know whats wrong. How do I get my table to show all the data and update each time new data is added?

import UIKit
import Firebase
import FirebaseDatabase

class FindPartiesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


var parties = [party]()

@IBOutlet weak var partyTable: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

partyTable.delegate = self
partyTable.dataSource = self

let ref = FIRDatabase.database().reference()

ref.child("parties").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let name = snapshotValue?["name"] as! String
let location = snapshotValue?["location"] as! String
let description = snapshotValue?["description"] as! String

self.parties.append(party(name: name, description: description, location: location))
})

}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// creates the number of cells in the table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parties.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// Make table cells the show the user name
var cell = partyTable.dequeueReusableCell(withIdentifier: "Cell")

let nameLabel = cell?.viewWithTag(1) as! UILabel
nameLabel.text = parties[indexPath.row].name

let locationLabel = cell?.viewWithTag(2) as! UILabel
locationLabel.text = parties[indexPath.row].location


return cell!
}

}


Here is my database setup:

testApp
parties
-KUUzxkssjWoSZ22QS8r
description: ""
location: "Here"
name: "party 1"
-KUV0ObFVbPyI_SJ0f3F
description: ""
location: "There"
name: "party 2"

Answer

You need to reload the table view after updating your data model:

ref.child("parties").queryOrderedByKey().observe(.childAdded, with: {
    snapshot in
    let snapshotValue = snapshot.value as? NSDictionary
    let name = snapshotValue?["name"] as! String
    let location = snapshotValue?["location"] as! String
    let description = snapshotValue?["description"] as! String

    self.parties.append(party(name: name, description: description, location: location))

    DispatchQueue.main.async {
        partyTable.reloadData()
    }
})
Comments