从firebase获取子节点(Swift)

时间:2017-08-01 19:48:24

标签: swift firebase firebase-realtime-database uicollectionview

如何从firebase获取子节点? Firebase结构在这里:

firebase struct

我需要为上面的每个孩子准备一个孩子“照片”。然后添加到collectionView每个孩子“照片”。

我的firebase结构:

{

"Студии" : {
 "Бабулька" : {
  "Photo" : {
    "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city3.jpg?alt=media&token=12a87c0c-ade1-43f9-b76b-ecdaa86cf185"
  },
  "address" : "Сатурн",
  "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city3.jpg?alt=media&token=12a87c0c-ade1-43f9-b76b-ecdaa86cf185",
  "image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city3.jpg?alt=media&token=12a87c0c-ade1-43f9-b76b-ecdaa86cf185",
  "name" : "Карапулька"
},
 "Дубаи" : {
  "Photo" : {
    "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city1.jpg?alt=media&token=c442fd8f-4cc4-4e30-8242-975aaf5427dc"
  },
  "address" : "Тутушка",
  "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city1.jpg?alt=media&token=c442fd8f-4cc4-4e30-8242-975aaf5427dc",
  "name" : "Дубаи"
},
 "Лондон" : {
  "Photo" : {
    "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/oko1.jpg?alt=media&token=fedea2cb-93b1-496c-9392-0b95f4ada7b5"
  },
  "address" : "Бейкер стрит",
  "image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/oko1.jpg?alt=media&token=fedea2cb-93b1-496c-9392-0b95f4ada7b5",
  "name" : "Лондон"
    }
  }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要获取所需数据,请迭代主父节点的所有子注释。假设以下结构

posts
   post_0
     Photo
       image: "https://www....."
   post_1
     Photo
       image: "https://www....."

以及获取图片网址的代码......

let ref = self.ref.child("posts")
ref.observeSingleEvent(of: .value, with: { snapshot in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let imageSnap = snap.childSnapshot(forPath: "Photo")
        let dict = imageSnap.value as! [String: Any]
        let url = dict["image"] as! String
        print(url)
    }
})