accessing nested firebase data in swift

2019-07-31 18:10发布

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"

2条回答
混吃等死
2楼-- · 2019-07-31 18:33

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)
查看更多
爷、活的狠高调
3楼-- · 2019-07-31 18:38

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
        }
    }
})
查看更多
登录 后发表回答