accessing nested firebase data in swift

情到浓时终转凉″ 提交于 2019-12-24 06:24:09

问题


I am working wth a data structure, and I am looping through a couple nodes and here is the json data I get.

Snap (20171012) {
"-KwM45HyW4UduQgKTGn6" =     {
    ImageName = "Screen Shot 2017-10-13 at 11.24.51 AM.png";
    fileURL = "";
    thumbFileUrl = "";
    user = "User not defined";
};
"-KwM4limD2aRyHgeKE5P" =     {
    ImageName = "test.png";
    fileURL = "";
    thumbFileUrl = "";
    user = "User not defined";
};

}

After this, I can access the "snap" value using my data.key to get the "20171012"

ref.child(myselected_spot!).observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            for mydata in snapshot.children.allObjects as! [DataSnapshot]
            {
                if mydata.key.characters.count == 8 {
                self.formattedDates.append(convertDate(stringDate: mydata.key))
                self.selected_dates.append(mydata.key)

How would I get the value for "ImageName"


回答1:


Your mydata is another DataSnapshot, so you can access all methods and properties of that class. In this case you're looking for DataSnapshot.childSnapshotForPath::

ref.child(myselected_spot!).observe(DataEventType.value, with: { (snapshot) in        if snapshot.childrenCount > 0 {
    for mydata in snapshot.children.allObjects as! [DataSnapshot]
    {
        if mydata.key.characters.count == 8 {
        self.formattedDates.append(convertDate(stringDate: mydata.key))
        self.selected_dates.append(mydata.key)
        print(mydata.childSnapshot(forPath: "ImageName").value)



回答2:


Pretty simple - I do not know what the variable myselected_Spot is but I am going to assume it's -KwM45HyW4UduQgKTGn6. If the below code does not yield results - I will need to know what that variable is.

ref.child(myselectd_spot).observe(.value, with: { (snapshot) in
    if snapshot.value is NSNull{
        //handles errors
        return
    }
    else{
        if let selectedSnapDict = snapshot.value as? NSDictionary {//Can also be [String: Any]
            print(selectedSnapDict["ImageName"] as! String) //We know it's a string
        }
        else{
            //null
        }
    }
})


来源:https://stackoverflow.com/questions/46993362/accessing-nested-firebase-data-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!