Ian Ian - 1 month ago 8
iOS Question

unable to append content to an array

This might seems complex but I guess it's actually pretty simple one.

I am trying to pass my date in firebase to tableviewCell in my VC

Here's my database structure

"2016-10-24 MON" : {
"types" : {
"LUNCH" : {
"TypeA" : "2", //the amount
"TypeB" : "1",
"TypeC" : "1"
},
"DINNER" : {
"TypeA" : "1",
"TypeB" : "2",
"TypeC" : "3"
}
}
}
"2016-10-26 WED" : {
"types" : {
"LUNCH" : {
"TypeA" : "0",
"TypeB" : "2",
"TypeC" : "3"
},
"DINNER" : {
"TypeA" : "2",
"TypeB" : "2"
}
}


and this is my code

class orderDetail: UIViewController, UITableViewDelegate, UITableViewDataSource{

var theARRAY : [(DATES: String, TimeDeliv: String, AmountA:String, AmountB: String, AmountC: String)] = []


override func viewDidLoad() {

theREF.observeSingleEvent(of: .value, with: { (snapshot) in
//theREF is my Firebase Reference



if let Date = snapshot.value as? [String:AnyObject]{
for each in Date {

let orderdate = each.0 as! String

theREF.child(orderdate).observe(.value, with: { (snapshot) in

if snapshot.hasChild("LUNCH") {

theREF.child(orderdate).child("LUNCH").observe(.value, with: {(snapshot) in

if let snapDict = snapshot.value as? Dictionary <String, AnyObject> {

let Num1 = snapDict["TypeA"] as? String
let Num2 = snapDict["TypeB"] as? String
let Num3 = snapDict["typeC"] as? String


self.theARRAY.append((DATES: "\(orderdate)", TimeDeliv:"LUNCH", AmountA:"TypeA \(Num1)", AmountB:"TypeB \(Num2)", AmountC :"TypeC \(Num3)"))

}

})


print("LUNCH works \(snapshot)")
} else {
print ("NONE")
}
})

}
}
}
)



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

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

let cell = tableView.dequeueReusableCell(withIdentifier: "DetailCell") as! detailCell!


cell?.detailMealTypeA.text = theARRAY.AmountA
cell?.detailMealtypeB.text = theARRAY.AmountB
cell?.detailMealtypeC.text = theARRAY.AmountC
// these are from UItableViewCell file


return cell!
}


what I am trying to do is I want to append details in Database to theARRAY and then shoe them in tableViewCell

but I keep getting 0 in numberOfRowsInSection and nil in cellForRowAt function!

otherwise I think these code should work !

I think it's because I call
theARRAY.append
at wrong line

can someone please help me out here :)

please excuse my nasty code btw.

Answer

When viewDidLoad is called, your tableview is configured right away without waiting for your Firebase call's completion.

Once you are done retrieving your data, you need to reflect these changes back and update your UI thread. Add the following line outside the for loop.

DispatchQueue.main.async
{
  self.tableView.reloadData()
}