【问题标题】:Firebase getting wrong snapshot back when asking for child with more children?当要求有更多孩子的孩子时,Firebase 得到错误的快照?
【发布时间】:2017-01-10 15:13:45
【问题描述】:

我无法从 Firebase 获取数据。我已经设置了三个测试数据集,每个项目都称为“活动”。对于每个“活动”,都可以有一个用户完成了活动,该活动将在活动 ID -> 用户 -> 用户 ID -> ConfirmImageUrl 和已完成的图像下进行。当我尝试拉出用户的孩子和用户的孩子时,我没有得到所有的数据。当没有用户时,它会正确地拉动它。

在 Firebase 中是这样设置的: Firebase Data Setup

在我的viewDidLoad 中,这就是我提取数据的方式。每个“活动”进入一个UITableViewCell

DataService.ds.DATABASE_BASE_CAMPAIGNS.observe(.value, with: { (snapshot) in
    print("menan check:\(snapshot.value!)")
    if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
        print("menan check: \(snapshot)")
        self.campaigns = []
        for snap in snapshot {
            if let campaignData = snap.value as? Dictionary <String, AnyObject> {
                let key = snap.key
                let campaign = Campaigns(campaignKey: key, campaignData: campaignData)
                print("menan check: \(campaignData)")
                self.campaigns.append(campaign)
            }
        }
    }
    self.tableView.reloadData()
})

这是输出: The Output from the snapshot received

我花了很长时间试图弄清楚?有谁知道怎么回事?

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    您的数据非常深,因此您需要更多字典来处理键值对。

    这里有一个快速解决方案来获取最深的数据,即确认值。它可以缩短,但我把它写得很冗长,所以可以逐行解释。

        campaignRef.observe(.value, with: { (snapshot) in
                for snap in snapshot.children { //iterate over 21hb, 989 huv etc
    
                    //contains all data in 21hb
                    let node = snap as! FIRDataSnapshot
    
                    // represent the data in the node as a dictionary
                    let nodeDict = node.value as! [String: AnyObject]
    
                    //grab just the users node, whose value is also a dictionary
                    let users = nodeDict["users"] as! [String: AnyObject]
    
                    //iterate over each user in the users node
                    for user in users {
                        let userId = user.key //this is the user id
    
                        //the value is a dictionary of key: value
                        // as in   confirm: url
                        let value = user.value as! [String: AnyObject]
    
                        //get the value for the confirm key, which is the url
                        let confirm = value["confirm"]
    
                        //print the user it and the confirm url
                        print("key = \(userId)  value = \(confirm!)")
                    }
                }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多