无法从 Firebase 实时数据库获取数据 - Swift / Firebase

问题描述

我正在尝试从实时数据库获取值并将其显示在 tableview 单元格上。我不确定为什么我无法获取值,但我相信它来自我的数据库参考。我的目标是检索项目的“重量”并将其显示在单元格的标签上。如果有人可以看看,我将不胜感激!

我的实时数据库

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
    }
}

Realtime Database

解决方法

通过查看您的代码,您将一个侦听器附加到路径 sf_merged <- st_intersection(nuts2,pop_grid) %>% mutate( intersection_area = as.numeric(st_area(.)),intersection_fraction = intersection_area / (1000*1000)) %>% mutate_at( .vars = c("Pop"),.funs = ~ (. * intersection_fraction) )%>% group_by(NUTS_ID) %>% summarise_at( .vars = c("Pop"),.funs = ~sum(.,na.rm=T) ) ,因此您将获得包含该路径下所有数据的快照,因此是所有天的所有项目。

您的回调将需要处理这两个嵌套级别,但它目前仅包含一个循环。因此,回调中的 /users/$uid/Journal 变量指向日期快照,而不是项目快照。

要解决此问题,请像这样嵌套两个循环:

item

顺便说一句:感谢您以这种方式命名 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] ... 变量,因为这样可以更容易地快速发现问题。 ?