无法从Firebase实时数据库获取数据-Swift/Firebase
我试图从实时数据库中获取值,并将其显示在tableview单元格中。我不确定为什么我无法获取值,但我相信这是从我的数据库引用中获取的。我的目标是检索项目的“重量”,并将其显示在单元格的标签上。如果有人能看一看,我会非常感激的 我的实时数据库:无法从Firebase实时数据库获取数据-Swift/Firebase,swift,uitableview,firebase-realtime-database,Swift,Uitableview,Firebase Realtime Database,我试图从实时数据库中获取值,并将其显示在tableview单元格中。我不确定为什么我无法获取值,但我相信这是从我的数据库引用中获取的。我的目标是检索项目的“重量”,并将其显示在单元格的标签上。如果有人能看一看,我会非常感激的 我的实时数据库: Users -> User Id -> Journal -> Date // this is chosen by the user and is saved, Ie; Friday, Apr 30, 2021
Users
-> User Id
-> Journal
-> Date // this is chosen by the user and is saved, Ie; Friday, Apr 30, 2021
-> Item // this is also chosen by the user and is saved, Ie; Milk
-> Weight: "20" // this is standard and must be entered by the user.
我的视图控制器:
class Test: UIViewController {
@IBOutlet weak var itemsList: UITableView!
var databaseRef: DatabaseReference!
var items = [Items]()
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = Database.database().reference().child("users/\(Auth.auth().currentUser)/Journal")
databaseRef.observe(DataEventType.value, with: {(snapshot) in
if snapshot.childrenCount>0 {
self.items.removeAll()
for item in snapshot.children.allObjects as! [DataSnapshot] {
let itemsObject = item.value as? [String: AnyObject]
let Weight = itemsObject?["Weight"]
let item = Items(Weight: (Weight as! String?)!)
self.items.append(item)
}
self.itemsList.reloadData()
}
})
}
}
extension Test: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = itemsList.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! JournalTableViewCell
let item: Items
item = items[indexPath.row]
cell.lblWeight.text = item.Weight
return cell
}
}
物品快捷
class Items {
var Weight: String
init(Weight: String) {
self.Weight = Weight
}
}
通过查看代码,您将侦听器附加到路径
/users/$uid/Journal
,因此您将获得一个包含该路径下所有数据的快照,以及所有日期的所有项目
您的回调将需要处理这两个嵌套级别,但它当前只包含一个循环。因此,回调中的项
变量指向日期快照,而不是项快照
要解决此问题,请按如下方式嵌套两个循环:
databaseRef.observe(DataEventType.value, with: {(snapshot) in
if snapshot.childrenCount>0 {
self.items.removeAll()
for date in snapshot.children.allObjects as! [DataSnapshot] {
for item in date.children.allObjects as! [DataSnapshot] {
let itemsObject = item.value as? [String: AnyObject]
...
顺便说一句:感谢您以这种方式命名
项
变量,因为它使快速发现问题变得更加容易。你好,弗兰克,谢谢你详细回答我的问题!我理解核心问题,所以我感谢你让我知道。我尝试了你的代码,但数据仍然没有被读取-我不太确定为什么会出现这种情况,但我正在使用代码作为构建步骤,以确定接下来的步骤。非常感谢您的回复。在这种情况下,您可能需要在调试器中运行代码,并从if snapshot.childrenCount>0
逐步执行代码。例如,item.key
应该是Milk
,然后可以进行检查。