Firebase和使用Swift读取嵌套数据 [英] Firebase and reading nested data using Swift

查看:44
本文介绍了Firebase和使用Swift读取嵌套数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Swift和Firebase创建一个简单的Instagram风格的应用程序,并且在从Firebase中读取每个图像帖子的注释时遇到了麻烦.

I am trying to create a simple Instagram style app using Swift and Firebase and I am running into trouble reading comments for each Image post from Firebase.

这里有几个问题:

  • 我在树的顶部放有帖子,然后在每个图像的键下都有每个用户添加的评论数据.在这种情况下,可以使用用户名作为密钥而不是childbyAutoId生成的密钥吗?

  • I have the Posts at the top of the tree and then the keys per image under which have data on the comments added by each user. Is it possible to use the username as the key instead of the key generated by childbyAutoId in this instance ?

我将如何读取userComment和UserName并将它们保存到可以在TableView中显示的数组中?

How would I read the userComment and UserName and save them into an Array that I can then display in a TableView ?

任何回应都值得赞赏.谢谢.

Any response is much appreciated. Thanks.

推荐答案

var postsCommentsDict : NSMutableDictionary = NSMutableDictionary()
var userNameArray : [String] = [String]() 
var userCommentArray : [String] = [String]()
FIRDatabase.database.reference().child("Posts").observeEventType(.Value, withBlock: {(Snapshot) in

if Snapshot.exists(){
    let imageD = Snapshot.value
    let imageD_ID = imageD.key
   //Retrieving the email and image name
     let imageName = imageD["userImage"] as! String
     let userEmail = imageD["userEmail"] as! String
    //Here you are accessing each image ID
    //First Question Alternative Completed

         //To answer the second Question :-

     FIRDatabase.database.reference().child("Posts").child(imageD_ID).child("comments").observeEventType(.Value, withBlock: {(Snapshot) in

  if let commentsDictionary = Snapshot.value {

    for each in commentsDictionary{

      postsCommentsDict.setObject(each["userName"] as! String , forKey : each["userComment"] as! String)
               //Saving the userName : UserComment in a dictionary
      userNameArray.append(each["userName"] as! String)
      userCommentArray.append(each["userComment"] as! String)
               //Saving the details in arrays
               //Prefer dictionary over Arrays

    }

} else {

   //no comments to append the arrays

        }

      })

   }
})

一旦您保存完注释字典:如何阅读:-

Once you are Done Saving the Comments dictionary : How to read it : -

for each in postsCommentsDict as! NSDictionary{
  let userNm = each.key
  let userComment = each.value
  //username and userComment's retrieved 

}

请忽略错别字,如果有的话!...希望有帮助.

Please ignore the Typos, if any!...hope this helps..

这篇关于Firebase和使用Swift读取嵌套数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆