【问题标题】:Swift Firebase access data inside child snapshot (by childAdded)Swift Firebase 访问子快照中的数据(通过 childAdded)
【发布时间】:2017-01-30 06:37:17
【问题描述】:

我之前发布了一个关于如何访问子快照中的数据的问题,我得到了一个非常有效的答案。然而,这个解决方案只允许我按值检索数据——而不是我的孩子。你看,我有一个这样的 JSON 树结构:

Players {

PlayerID {

Username

Rank

Achievements {

Rookie: yes

}


}

然后我意识到我真的需要在“成就”下有多个“childByAutoId”——看起来像这样:

Player {

PlayerID {

Username

Rank

Achievements {

autoID1 {

isAchieved: yes

}

autoID2 {

isAchieved: yes 

}

}

}

那么我将如何继续尝试获取每个 childByAutoId 的 ChildValues 呢?我知道这适用于观察快照上的“ChildAdded”,但是 - 这似乎不是这里的功能。

这是我现在拥有的代码:

 if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements") as? FIRDataSnapshot{

                if let achievementDictionary = childSnapshot.value as? [String:AnyObject] , achievementDictionary.count > 0{

                    if let achieveMedal = achievementDictionary["Rookie"] as? String {

                        print(achieveMedal)

             }        
       }
    }

我们将不胜感激!

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    这样的 JSON 树结构怎么样:-

    Achievements : {
    
     achievement1 : true,
     achievement2 : true,
     achievement3 : false,
     achievement4 : true,
    
    }
    

    检索您的成就:-

    if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements") as? FIRDataSnapshot{
    
                if let achievementDictionary = childSnapshot.value as? [String:AnyObject] , achievementDictionary.count > 0{
    
                   for each in achievementDictionary{
                      print(each.0) // achievement name
                      print(each.1)  // isAchieved (true/false)
                   }
    
             }        
       }
    }
    

    出于导航原因,不建议在数据库中添加如此深的节点。

    但此代码也适用于 childByAutoID 的情况,即 each.0 将成为您的自动 ID,而 each.1 将成为该 ID 对应的字典。对于该词典的更深入细节只需浏览词典即可

    【讨论】:

    • 问题是我需要在我也需要的每个“childByAutoId”中提供更多数据。嗯..不可能吗?
    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2017-07-27
    • 2017-03-26
    • 2016-04-09
    • 2019-01-12
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多