我正在尝试使用Swift和Firebase创建一个简单的Instagram风格的应用程序,我在为Firebase中的每个Image帖子阅读评论时遇到了麻烦。
这里有几个问题:
我在树的顶部有帖子,然后每个图像的键在其下面有每个用户添加的注释数据。在这种情况下,是否可以使用用户名作为密钥而不是childbyAutoId生成的密钥?
我如何阅读userComment和UserName并将它们保存到一个我可以在TableView中显示的数组?
非常感谢任何回应。感谢。
答案 0 :(得分:2)
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
}
})
}
})
一旦完成保存评论词典:如何阅读: -
for each in postsCommentsDict as! NSDictionary{
let userNm = each.key
let userComment = each.value
//username and userComment's retrieved
}
如果有的话,请忽略错别字!...希望这有帮助..