【问题标题】:Get child nodes from firebase (Swift)从 firebase (Swift) 获取子节点
【发布时间】:2017-08-01 19:48:24
【问题描述】:

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

我需要为上面的每个孩子获取一个孩子的“照片”。然后将每个子“照片”添加到 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" : "Лондон"
    }
  }
}

感谢您的帮助。

【问题讨论】:

  • 请将您的 Firebase 结构发布为文本,而不是图像。这样,如果我们需要在答案中使用结构,我们就不必重新输入它。您可以从 Firebase 控制台->三个点->导出 JSON 以文本形式获取 Firebase 结构
  • 感谢您的帮助。我添加了有问题的 firebase 结构。

标签: swift firebase firebase-realtime-database uicollectionview


【解决方案1】:

要获取您想要的数据,请遍历主父节点的所有子注释。假设如下结构

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)
    }
})

【讨论】:

  • 谢谢,它有效;)也许你可以提示如何加载图像数组?例如,如果在每个“照片”中,我将有“image1”、“image2”、“image3”或更多或更少。
  • 不要将数据存储在 Firebase 阵列中,因为 Firebase 阵列是邪恶的,请参阅我对 this question 的回答。它们可以存储为 key: value 对,其中 key 由 childByAutoId 生成。所以它会是 images/firebase_key_0: image0 和 /images/firebase_key_1: image1 等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2019-01-03
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多