【发布时间】:2016-06-20 08:48:32
【问题描述】:
我正在尝试创建用户参与的聊天的 tableView。我正在关注他们网站上的 firebase 教程,他们说要轻松获取用户所属的聊天室列表,以创建一个孩子并将房间的名称添加到该孩子。
所以我的结构是这样的
Users
UNIQUE KEY
nickname: "name"
rooms
name: true
Room
etc etc
所以在我的 cellForRow 中我使用了这段代码
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
}
我收到一个错误,当我 PO 名称时它会出现一个空字符串
有人可以帮助我了解问题所在以及如何解决吗?谢谢
编辑 1
我已经让代码部分工作
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
}
现在的问题是 firebase 中有 2 个项目...而且它只显示其中一个
【问题讨论】:
-
我会观察 cellForRowAtIndexPath 之外的整个数组。例如在 viewDidAppear 中。然后,一旦您从 fetch 中获得项目,就重新加载 tableview。
-
我的问题在于 self.names....我收到错误 EXC_BAD_Instruction....
-
您对 firebase 的调用是在回调中 - 所以您设置它的整个方式都是错误的。将 firebase 调用移至我上面所说的位置,而不是在该委托方法中。
-
你不明白,我这样做了,但仍然有同样的问题
-
在循环中执行 print(user) - 注释掉给你一个错误的部分,看看你得到了什么
标签: swift firebase firebase-realtime-database