【问题标题】:Accessing son data Firebase访问儿子数据 Firebase
【发布时间】:2016-04-27 06:11:15
【问题描述】:

我有一个问题,我正在尝试访问 firebase 上的一些数据,这是数据结构

我设法访问了“收藏夹” 这是我以前得到的

ref.observeEventType(.Value, withBlock: { snapshot in
        let fav = snapshot.value.objectForKey("favPost")
        print("\(fav) Printed")
    })

但我正在尝试访问“favPost”但我无法弄清楚?!!


Firebase 结构

{
  "posts" : {
"-KGIxJybfQEJbcSy2bHH" : {
  "author" : "Rioodi",
  "postText" : "Test",
  "votes" : 1
},
"-KGIxLUmPIa1Q1k0oRLs" : {
  "author" : "Rioodi",
  "postText" : "Raed",
  "votes" : 0
},
"-KGJe-5ciAyu6Kom98E0" : {
  "author" : "Neal",
  "postText" : "Neal",
  "votes" : 0
},
"-KGLFC0RqW_48lHMCsx8" : {
  "author" : "Rioodi",
  "postText" : "Test",
  "votes" : 0
}
  },
  "users" : {
"afd0f27a-f62f-4cf1-9e81-032edc246687" : {
  "email" : "test@test.com",
  "favorite" : {
    "-KGIxJybfQEJbcSy2bHH" : {
      "favPost" : "Test"
    }
  },
  "provider" : "password",
  "username" : "Rioodi"
},
"fc56cc22-6275-48e0-8376-0b73b273b8e2" : {
  "email" : "tests@test.com",
  "provider" : "password",
  "username" : "Neal"
}
  }
}

【问题讨论】:

  • 请将您的 Firebase 结构发布为文本!您可以使用 Firebase 仪表板中的“导出”按钮轻松获取。
  • 好的,我发布了 firebase 结构

标签: ios json swift firebase


【解决方案1】:

由于您知道 userId,并且您也知道您正在寻找他们最喜欢的帖子,因此可以这样直接访问它。

let usersRef = self.myRootRef.childByAppendingPath("users")
let thisUserRef = usersRef.childByAppendingPath("this users id")
let thisUserFavoriteRef = thisUserRef.childByAppendingPath("favorite")

thisUserFavoriteRef.observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
    let fav = snapshot.value["favPost"] as! String
    print(fav)

})

你也可以将路径合并成一行

let thisUserFavoriteRef = rootRef.childByAppendingPath("users/this users id/favorite")

【讨论】:

  • 我用了你所说的,但是 (snapshot.key) 打印了“最喜欢的”,而 (snapshot.value) 打印了“所有字典”,为什么?!
  • @Rioodi 圣牛,我很抱歉。我在回答中打错了。 .Value 事件应该是 .ChildAdded,并且打印语句不正确。我已经更新了实际 work 的答案。您可能应该为可选的 nil 添加代码... if let fav = snapshot.value["favPost"] as?如果有可能为 nil,则为 String {}。
【解决方案2】:

您可以尝试以下代码。 (可根据需要更改。)

 ref.observeEventType( .Value, withBlock: { snapshot in

           //lets consider you have reached up to "favarites"

      let favarites = snapshot?.value as! [ String : [ String : AnyObject ] ]

      //In "favarites" array you will get whole list  
      for favarite in favarites
      {
          let favPost = favarite.1[ "favPost" ] as? String  //to access value part
          print("\(favPost) Printed"
       }               
     }

【讨论】:

  • 如果值为 Null 应用会崩溃怎么办
  • 别着急解决了先检查NSNull ^_^
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
  • 2023-01-16
  • 1970-01-01
  • 2017-09-24
相关资源
最近更新 更多