我已经和Firebase一起工作了一段时间,没有问题,但是最近我有一个包含多个child的数据库结构,我在阅读代码时遇到了问题。
这是我的Firebase数据库结构:

{
  "news" : {
    "50OzNLsK" : {
      "category" : "Anuncio",
      "content" : [ null, {
        "paragraph" : {
          "text" : "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      }, {
        "quote" : {
          "image" : "http://www.magonicolas.cl",
          "quoteText" : "textoDelQuote"
        }
      } ],
      "date" : "Hoy",
      "imgURL" : "https://firebasestorage.googleapis.com/v0/b/rinnofeed.appspot.com/o/images%2Ftanta.jpg?alt=media&token=60f18a95-9919-4d81-ab1c-9976b71590fc",
      "likes" : 12,
      "summary" : "Este es el resumen de la noticia",
      "title" : "Mi NUeva noticia",
      "videoURL" : "https://youtu.be/S0YjUc7K3cw"
    }
  },
  "users" : {
    "tfeMODxXUnVvhvzntm77pKKtyfz2" : {
      "email" : "magonicolas@gmail.com",
      "store" : "Rinno"
    },
    "tpjn4feUuiTJmsd9lslHTREG1iE2" : {
      "email" : "nicolas.palacios@rinno.la",
      "store" : "Rinno"
    }
  }
}

我的问题是读取内部信息,例如500zNLsK/content/1/parahraph/text中的文本或500zNLsK/content/2/quote/quoteText中的引号文本
我走了这么远:
DataService.ds.REF_NEWS.queryOrdered(byChild: "date").observe(.value, with: {(snapshot) in

            self.news = []


            if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for snap in snapshot
                {
                    if let newsDict = snap.value as? Dictionary<String, AnyObject>
                    {
                        print("Mago Dict: \(newsDict)")

                        let key = snap.key
                        let new = News()
                        new.configureNews(newsKey: key, newsData: newsDict)
                        self.news.append(new)

                    }
                }
            }

我不能让里面的内容出现,它给出空值。
非常感谢您的帮助:D

最佳答案

您需要对结构进行许多更改,才能使其流畅地工作。下面是一个示例结构,让您朝着正确的方向前进:

  "news"
    "topic_1"
      "category" : "topic 1 category"
      "content"
        "content_1"
          "paragraph"
            "text" : "topic 1 content 1 text"
        "content_2"
          "paragraph"
            "text" : "topic 1 content 2 text"
      "date" : "some date",
      "likes" : 12

    "topic_2"
      "category" : "topic 2 category",
      "content"
        "content_1"
          "paragraph"
            "text" : "topic 2 cotent 1 text"
        "content_2"
          "paragraph"
            "text" : "topic 2 content 2 text"
      "date" : "another date",
      "likes" : 425

以下是注释代码,用于获取“内部”大多数数据
  newsRef.observe(.value, with: { snapshot in

    if ( snapshot!.value is NSNull ) {
        print("not found")
    } else {

        for child in (snapshot?.children)! {

            //snapshots are each node withing news: topic_1, topic_2
            let snap = child as! FDataSnapshot

            //get each nodes data as a Dictionary
            let dict = snap.value as! [String: AnyObject]

            //we can now access each key:value pair within the Dictionary
            let cat = dict["category"]
            print("category = \(cat!)")

            let likes = dict["likes"]
            print("  likes = \(likes!)")

            //the content node is a key: value pair with 'content' being the key and
            //  the value being a dictionary of other key: value pairs
            let contentDict = dict["content"] as! [String: AnyObject]

            //notice that the content_1 key: value pair has a key of content_1
            //   and a value of yet another Dictionary
            let itemNum1Dict = contentDict["content_1"] as! [String: AnyObject]

            //new we need to get the value of content_1, which is
            //  'paragraph' and another key: value pair
            let paragraphDict = itemNum1Dict["paragraph"] as! [String: AnyObject]

            //almost there.. paragraphDict has a key: value pair of
            //   text: 'topic 1 content 1 text'
            let theText = paragraphDict["text"] as! String
            print("  text = \(theText)")

        }
    }
})

一些注释:
1)请不要在Firebase中使用数组。他们是邪恶的,会使你非常悲伤。节点名应该是描述节点(如“news”)和使用childByAutoId创建的子值的内容。即使在“content”节点中,我也使用了content\u 1和content\u 2,但这些也应该使用childByAutoId创建
2)如果像我的示例那样在节点上迭代,那么节点内的结构应该保持一致。实际上,您可以绕过这一点,但对于查询等,始终最好保持一致。
3)Denormalizing is Normal。这种结构可以工作,但是你会获得一些优势,使整个结构变浅。

关于swift - 从具有多个子项的Firebase数据库中检索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40995752/

10-14 21:24
查看更多