Reputation:
I am trying to create a tableView of chats the user is a part of. I was following the firebase tutorials on their site and they said to easily get a list of chat rooms the user is a part of to create a child and add the names of the rooms to that child.
So my structure looks like this
Users
UNIQUE KEY
nickname: "name"
rooms
name: true
Room
etc etc
So in my cellForRow I used this code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
firebase.child("users").child(fUID).observeSingleEvent(of: .value, with: { snapshot in
for user in snapshot.children.allObjects as! [FIRDataSnapshot]{
self.names = (user.value?["participating"] as? String)!
}
})
cell.textLabel?.text = self.names
cell.detailTextLabel?.text = "test"
return cell
}
I get a error and when I PO the names it comes up with an empty string
Can somebody help me understand what is wrong and how to fix it? Thank you
EDIT 1
I have gotten the code to partially work
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let ref = firebase.child("users").child(fUID).child("participating")
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.value)
var dict = [String: Bool]()
dict = snapshot.value as! Dictionary
for (key, _) in dict {
self.names = key
print(self.names)
}
self.rooms.append(self.names)
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.rooms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.rooms[indexPath.row]
cell.detailTextLabel?.text = "test"
return cell
}
The issue now is that there is 2 items in the firebase...and it is only showing one of them
Upvotes: 1
Views: 1187
Reputation: 35677
The code you are using is the challenge. Here's a simplified version:
let usersRef = firebase.child("users")
let thisUser = usersRef.childByAppendingPath(fUID)
let thisUsersRooms = thisUser.childByAppendingPath("rooms")
thisUsersRooms.observeSingleEventOfType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found")
} else {
for child in snapshot.children {
let roomName = child.key as String
print(roomName) //prints each room name
self.roomsArray.append(roomName)
}
self.myRoomsTableView.reloadData()
}
})
That being said, this code should be called from within viewDidLoad to populate an array, and then as the tableView is refreshed the data should be pulled from that array to populate your cellView.
Upvotes: 1