ios - Firebase Database to UITableView Cell Problems -
i creating app uses firebase database display 2 different child databases within 1 cell. so, since first child database called "name", main text of cell, , second child database, "imageurl", subtitled text of cell.
i not able figure out why whenever try second child database table view cell, doesn't work. either index out of range error, or second child database doesn't show @ all.
here code:
variables:
@iboutlet weak var mytextfield: uitextfield! @iboutlet weak var mynamefield: uitextfield! @iboutlet weak var mytableview: uitableview! var ref: databasereference! var mynamelist:[string] = [] var mylist:[string] = [] var handle:databasehandle! var namehandle: databasehandle!
button code when save button pressed:
@ibaction func savebtn(_ sender: any) { if mynamefield.text != "" { ref?.child("name").childbyautoid().setvalue(mynamefield.text) mynamefield.text = "" if mytextfield.text != "" { ref?.child("imageurl").childbyautoid().setvalue(mytextfield.text) mytextfield.text = "" } } }
tableview function numberofrowsinsection code:
func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int { return mylist.count }
tableview function cellforrowatindexpath code:
func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell { let cell = uitableviewcell(style: .subtitle, reuseidentifier: "cell") cell.textlabel?.text = mynamelist[indexpath.row] cell.detailtextlabel?.text = mylist[indexpath.row]
viewdidload code:
override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. ref = database.database().reference() handle = ref?.child("imageurl").observe(.childadded, with:{ (datasnapshot) in if let item = datasnapshot.value as? string{ self.mylist.append(item) self.mytableview.reloaddata() } }) namehandle = ref?.child("name").observe(.childadded, with:{ (datasnapshot) in if let nameitem = datasnapshot.value as? string{ self.mylist.append(nameitem) self.mytableview.reloaddata() } }) }
my main.storyboard:
i notice couple of things might causing issue.
in cellforrowat
function, populating textlabel
array called mynamelist
, , populating detailtextlabel
array called mylist
. however, when you're loading data in viewdidload
, you're appending both contents mylist
. copy/paste error, think 1 of should mynamelist
.
also, data structure flawed. in cellforrowatindexpath
, based on how you're indexing rows (using indexpath.row
), you're assuming items come in pairs , 2 refs have same amount of children. based on savebtn
, can enter name
, not imageurl
, , it'll save name
, , whole database mismatched. i'd suggest having single child ref called items
, each 1 has name
, imageurl
.
Comments
Post a Comment