【发布时间】:2019-11-04 01:40:08
【问题描述】:
我正在尝试用我帖子中的 cmets 填充我的 cmetsTable。我有以下数据库结构 JSON:
{
"posts" : {
"-Lhu-XRs806sXSEQS2BF" : {
"reports" : 0,
"text" : "How can I improve my data structure?",
"timestamp" : 1561120090116,
"title" : "Hello Stack Exchange",
"userID" : "nyRBXSyyDhc1Qkypou0Iz0iMsyr1"
},
"-Lhu-fI6DMSZvy8EdIgM" : {
"reports" : 0,
"text" : "As in Libre",
"timestamp" : 1561120126347,
"title" : "Free",
"userID" : "nyRBXSyyDhc1Qkypou0Iz0iMsyr1"
},
"comments" : {
"-Lhu-hXISy-0N2V4ES-a" : {
"reports" : 0,
"timestamp" : 1561120135594,
"userID" : "nyRBXSyyDhc1Qkypou0Iz0iMsyr1"
},
"-Lhu-j1cR6V407tyUYY1" : {
"reports" : 0,
"timestamp" : 1561120141801,
"userID" : "nyRBXSyyDhc1Qkypou0Iz0iMsyr1"
},
"-Lhu-lrJp9H8SQowlYWz" : {
"reports" : 0,
"timestamp" : 1561120153314,
"userID" : "nyRBXSyyDhc1Qkypou0Iz0iMsyr1"
},
"posts" : {
"-Lhu-XRs806sXSEQS2BF" : {
"comments" : {
"-Lhu-hXISy-0N2V4ES-_" : "How is it going?",
"-Lhu-j1cR6V407tyUYY0" : "It’s good to see you"
}
},
"-Lhu-fI6DMSZvy8EdIgM" : {
"comments" : {
"-Lhu-lrJp9H8SQowlYWy" : "Richard Stallman"
}
}
}
}
}
}
还有下面的评论类:
class Comment {
var id:String
var text:String
init(id: String, text:String) {
self.id = id
self.text = text
}
}
考虑到您的建议后,这是我的代码:
var comments = [Comment] ()
@IBOutlet weak var commentsTable: UITableView!
@IBOutlet weak var commentPlaceHolder: UILabel!
@IBOutlet weak var newCommentLabel: UITextView!
weak var delegate:NewPostVCDelegate?
let ref = Database.database().reference().child("posts")
@IBAction func reply(_ sender: UIButton) {
let userID = (Auth.auth().currentUser?.uid)!
addComment(toPostId: post!.id, andComment: newCommentLabel.text, commentByUid: userID)
loadComments(forPostId: post!.id)
comments.removeAll()
commentsTable.reloadData()
newCommentLabel.text = String()
commentPlaceHolder.isHidden = false
}
func addComment(toPostId: String, andComment: String, commentByUid: String) {
let commentsRef = self.ref.child("comments") //ref to the comments node
let thisCommentRef = commentsRef.child(toPostId) //ref to a node with postId as key
let commentToAddRef = thisCommentRef.childByAutoId() //each comment will have it's own key
let d = [
"comment_text": andComment,
"comment_by_uid": commentByUid]
commentToAddRef.setValue(d)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadComments(forPostId: post!.id)
}
func loadComments(forPostId: String) {
let ref = self.ref.child("comments")
let thisPostRef = ref.child(forPostId)
thisPostRef.observeSingleEvent(of: .value, with: { snapshot in
let allComments = snapshot.children.allObjects as! [DataSnapshot]
for commentSnap in allComments {
let commenterUid = commentSnap.childSnapshot(forPath: "comment_by_uid").value as? String ?? "No uid"
let commentText = commentSnap.childSnapshot(forPath: "comment_text").value as? String ?? "No comment"
let aComment = Comment(id: commenterUid, text: commentText)
self.comments.append(aComment)
print(commenterUid, commentText)
}
self.commentsTable.reloadData()
})
}
func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.isScrollEnabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
self.commentsTable.dataSource = self
let cellNib = UINib(nibName: "CommentTableViewCell", bundle: nil)
commentsTable.register(cellNib, forCellReuseIdentifier: "postCell")
view.addSubview(commentsTable)
commentsTable.register(LoadingCell.self, forCellReuseIdentifier: "loadingCell")
self.commentsTable.delegate = self
mainText.isEditable = false
titleText.isEditable = false
commentsTable.register(cellNib, forCellReuseIdentifier: "postCell")
view.addSubview(commentsTable)
commentsTable.register(LoadingCell.self, forCellReuseIdentifier: "loadingCell")
print(delegate!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! CommentTableViewCell
cell.set(comment: comments[indexPath.row])
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "loadingCell", for: indexPath) as! LoadingCell
cell.spinner.startAnimating()
return cell
}
}
func textViewDidChange(_ commentView: UITextView) {
commentPlaceHolder.isHidden = !newCommentLabel.text.isEmpty
}
结合 Jay 的 cmets,我可以运行视图。我必须添加 cmets.removAll(),这样它就不会在 cmetsTable 中多次打印出 cmets。但是,func textViewDidChange 不再起作用。我不知道如何解决这个问题。我尝试调用该函数没有运气。也许委托变更会影响到这一点?
【问题讨论】:
-
你的主要问题是
let comment = Comment(id: childDataSnapshot.key, text: comments)你应该通过text而不是comments -
我不知道如何调用每个评论文本,因为每个评论文本都与一个唯一 ID 相关联,例如“-Lht1KEhkJR7ZPTcDqn8”或“-Lht1M76Bu9kTXJDezPp”
-
我删除了我的答案。除了错误之外,整个 JSON 解析都无法正常工作,例如 JSON 中根本没有
id键。目前还不清楚用户 ID 与-Lht...字典键的关系。 -
@RyanSchiller,在您的代码中,
let text = dict["comments"] as? [String:Any]部分的作用是什么?我想这是你的文字。注意:我假设您解析的部分是正确的。 -
在代码中将
let comment = Comment(id: childDataSnapshot.key, text: comments)替换为let comment = Comment(id: childDataSnapshot.key, text: text)。那应该可以。
标签: ios json swift firebase firebase-realtime-database