【问题标题】:Appending an array within a post rather than creating a new post在帖子中添加数组而不是创建新帖子
【发布时间】:2019-06-17 17:44:04
【问题描述】:

我正在尝试为我的开源社交媒体应用创建评论部分。我有一个帖子表。当您单击此表中的帖子时,它会将您带到 MainViewController,您可以在其中阅读这些帖子上的 cmets 并发表您自己的评论。 Post类如下:

import Foundation

class Post {
var id:String
var title: String
var text:String
var createdAt:Date
var comment: [String] = []

init(id: String, title: String,text:String,  timestamp:Double, comment: [String] = []) {
    self.id = id
    self.title = title
    self.text = text
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)




}
static func parse(_ key:String, data:[String:Any]) -> Post? {
    if let title = data["text"] as? String,
        let text = data["title"] as? String,
        let timestamp = data["timestamp"] as? Double {
        return Post(id: key, title: title,  text: text, timestamp:timestamp, comment: [])
        }


    return nil
    }
}

而MainTextViewController的代码如下:

import Foundation
import UIKit
import Firebase

class MainTextView: UIViewController, UITextViewDelegate{

@IBOutlet weak var titleText: UILabel!
@IBOutlet weak var mainText: UILabel!

@IBOutlet weak var commentsTable: UITableView!
@IBOutlet weak var commentPlaceHolder: UILabel!
@IBOutlet weak var newCommentLabel: UITextView!
weak var delegate:NewPostVCDelegate?

@IBAction func reply(_ sender: UIButton) {

// Firebase code here
    let postRef = Database.database().reference().child("posts").childByAutoId()

    let postObject = [
        "comment": newCommentLabel.text,
        "timestamp": [".sv": "timestamp"]
        ] as [String : Any]

    postRef.setValue(postObject, withCompletionBlock: { error, ref in
        if error == nil {
            self.delegate!.didUploadPost(withID: ref.key!)
            self.dismiss(animated: true, completion: nil)
        }  else {
            // Handle error

        }
    })
    newCommentLabel.text = String()
    commentPlaceHolder.isHidden = false
}
var post: Post?

// MARK: - View Controller LifeCycle

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.setMain()

}
override func viewDidLoad() {
    super.viewDidLoad()
    print(delegate!)
    commentsTable.dataSource = post?.comment as? UITableViewDataSource
    newCommentLabel.delegate = self


}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return post!.comment.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->   UITableViewCell {
    let cell = UITableViewCell()
    let label = UILabel(frame: CGRect(x:0, y:0, width:200, height:50))
    cell.addSubview(label)
    return cell
}


// UITableViewDelegate Functions

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 50
}

private func setMain() {
    guard let post = self.post else {
        return
    }

    titleText.text = post.text
    mainText.text = post.title
}
func textViewDidChange(_ commentView: UITextView) {

    commentPlaceHolder.isHidden = !newCommentLabel.text.isEmpty

    }
}

这是我的数据库结构:

  {
  "posts" : {
    "-LhaxLOSY3UI7tDUrCA_" : {
      "text" : "Nelson",
      "timestamp" : 1560800488059,
      "title" : "Hey\t"
    },
    "-LhaxbnjgDP7tdb7Eq_4" : {
      "text" : "Lol",
      "timestamp" : 1560800558514,
      "title" : "How’s it going"
    },
    "comment" : {
      "comment" : "Howdy"
    }
  }
}

我希望当我发表评论时,它会在帖子的 cmets 数组中附加一条新评论。然后每个人都可以将 cmetsTable 中的 cmets 视为数组中字符串的集合,最旧的字符串位于顶部。

目前,创建一条新评论会在 Firebase 中创建一个新帖子,其中只有一条评论作为单个字符串和一个时间戳。您将如何解决此问题,以便 post 按钮附加表格并且 cmetsTable 显示数组中的字符串?如果您需要我发布更多详细信息,请告诉我。谢谢你的帮助。

【问题讨论】:

  • 请不要在 NoSQL 数据库中使用数组。它们很难使用,并且正如您发现的那样,它们不能像使用代码中的典型数组那样真正使用。一般来说,数组是邪恶的,所以请参阅this question and answer。这个问题确实包含太多代码,而且有点不清楚您要做什么。听起来当用户添加帖子时,您想将其附加到现有帖子中?如果是这样,您能否包含您的 Firebase 结构的 sn-p?
  • 我会检查的。这是我的数据库的截图:imgur.com/a/Ml4KwS3
  • 最好将代码和结构包含为文本,而不是链接和图像。要获取您的 Firebase 结构,请使用 Firebase 控制台->导出 JSON,然后复制并粘贴您的结构的 sn-p。见images and links are evil。请将其包含在您的 question 中,因为链接断开会使问题无效。您可能还想澄清 comment 节点的用途 - 这应该是要发布的评论吗?每个帖子可以有多个评论吗? 评论还有哪些其他数据?
  • 每个帖子可以有多个评论。它们将像 4Chan 一样按时间顺序发布。我想给 cmets 加上时间戳并跟踪报告评论的次数。我为要应用于 cmets 的帖子制作了此报告功能:“func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let more = UITableViewRowAction(style: .default, title: "Report ") { action, index in self.posts.remove(at: indexPath.row) }" 我想跟踪每个帖子和评论收到多少报告以进行审核。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

不用过多的代码,从概念上讲,如果您想拥有一系列帖子,然后每个帖子还可以附加 cmets,这是结构的一个选项。

posts
   post_id_0
      text: "some text"
      timestamp: "20190601"
      title: "post title"
      post_uid: "uid_0"

comments
   comment_id_0
      belongs_to_post: "post_id_0"
      comment: "a comment about the post"
      timestamp: "20190601"
      comment_uid: "uid_49"
   comment_id_1
      belongs_to_post: "post_id_0"
      comment: "check out that first post!"
      timestamp: "20190602"
      comment_uid: "uid_102"

users
   uid_0
      name: "Leroy"

然后将观察者附加到帖子和 cmets。发布新帖子时,您会收到该帖子的通知,您可以将其添加到您的 tableView 数据源并刷新 tableView。

添加新评论时,您会收到该评论的通知并将其添加到 cmets dataSource 并重新加载 cmets tableView。添加新帖子:

let thisPostRef = your_firebase.posts.childByAutoId()
thisPostRef.setValue(your_post_data)

并添加评论

let postKey = the_post.key
let commentRef = your_firebase.comments.childByAutoId()
commentRef.setValue(your_comment_data)

并且 your_comment_data 将包含一个子节点 'belongs_to_post: postKey'

您还可以在某些帖子、某些用户发布的帖子上查看 cmets,甚至可以按日期或日期范围查询 cmets。

代码方面,posts 和 cmets 节点都是使用 .childByAutoId 创建的 - 最好将节点键与它们包含的数据分离,除非它是静态数据,如 uid。

如果您想增加一点灵活性,您也可以在其相关 cmets 的每个帖子中保留一个子节点。

posts
   post_id_0
      text: "some text"
      timestamp: "20190601"
      title: "post title"
      post_uid: "uid_0"
      comments:
         comment_id_0: true
         comment_id_1: true

但这取决于您要运行的查询类型。

注意:我将 cmets 结构与帖子节点分开,因为在运行查询时非规范化数据非常有用。

【讨论】:

  • 要学习实现这些类型的结构并将它们应用到我的代码中并在我的 tableViews 中呈现它们,您会推荐 Firebase 文档还是有更直接的资源?
  • @RyanSchiller Firebase 文档非常好,可以帮助您入门。有几个优秀的资源NoSQL data modeling 较旧但非常重要。如果您是 SQL'er Firebase For SQL。 Firebase 团队也在 youtube 上提供了一些视频。最后,是这个网站。 SO 有大量的问答,几乎涵盖了与 Firebase 打交道的所有内容。
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 2017-05-21
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
相关资源
最近更新 更多