我正在使用一个数据结构,我循环遍历几个节点,这是我得到的json数据。
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";
};
}
在此之后,我可以访问" snap"使用我的data.key来获得" 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)
我如何获得" ImageName"
的值答案 0 :(得分:2)
您的mydata
是另一个DataSnapshot
,因此您可以访问all methods and properties of that class。在这种情况下,您正在寻找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)
答案 1 :(得分:0)
非常简单 - 我不知道变量myselected_Spot
是什么,但我会假设-KwM45HyW4UduQgKTGn6
。如果下面的代码没有产生结果 - 我将需要知道该变量是什么。
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
}
}
})