当前位置: 首页 > 知识库问答 >
问题:

如何使用Firestore数据库在swift中为tableview中的项目列表设置后置键?

薛欣荣
2023-03-14

Post模型Swift文件

import Foundation
import Firebase
import FirebaseFirestore

protocol DocumentSerializable  {
    init?(dictionary:[String:Any])
}

struct Post {
   // var name:String
   // var content:String
    //var timeStamp:Date
     var username: String!
     var postTitle: String!
    // var postKey:  String!
     var postcategory:  String!
     var postContent:  String!

    //private var _postRef: DocumentReference!

    var dictionary:[String:Any] {
        return [
            "username": username,
            //"profile_pic":profile_pic,
            "postTitle":postTitle,
            "postcategory":postcategory,
            "postContent":postContent
          //  "postKey":postKey
        ]
    }
}

extension Post : DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard  let username = dictionary["username"] as? String,
           // let profile_pic = dictionary["profile_pic"] as? String,
            let postTitle = dictionary["postTitle"] as? String,
            let postcategory = dictionary["postcategory"] as? String,
            let postContent = dictionary["postContent"] as? String   else { return nil }

          //  let postKey = dictionary["postKey"] as? String

        self.init(username: username, postTitle: postTitle, postcategory: postcategory, postContent: postContent )
    }
}

用于在tableview中登记帖子的ViewController类

import Foundation
import UIKit
import Firebase

class HomeViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()
    var db: Firestore!        

    private var documents: [DocumentSnapshot] = []
    //public var posts: [Post] = []
    private var listener : ListenerRegistration!    

    override func viewDidLoad() {
        super.viewDidLoad()

        db = Firestore.firestore()

        self.navigationController?.navigationBar.isTranslucent = false
        tableView = UITableView(frame: view.bounds, style: .plain)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
        view.addSubview(tableView)

        var layoutGuide:UILayoutGuide!

        if #available(iOS 11.0, *) {
            layoutGuide = view.safeAreaLayoutGuide
        } else {
            // Fallback on earlier versions
            layoutGuide = view.layoutMarginsGuide
        }

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()

        retrieveAllPosts()            
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func handleLogout(_ sender:Any) {
        try! Auth.auth().signOut()
        self.dismiss(animated: false, completion: nil)
    }

    func retrieveAllPosts(){
        let postsRef = Firestore.firestore().collection("posts").limit(to: 50)

        postsRef.getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")

                    self.posts = querySnapshot!.documents.flatMap({Post(dictionary: $0.data())})
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }                                   
                }
            }
        }

    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }
}

共有1个答案

巫马磊
2023-03-14

它将不是一个简单的帖子键,你将需要创建名为“评论”的帖子喜欢子文档,在该列表中,你将需要添加评论内容,用户,图瑟,帖子等。只添加postKey不会解决您的问题

下面是一个简单的例子

let postId = "45f4854fjrh4"   // documentId of post
    let commentData = [commentContent:"this is comment", "commenterId":"242343f3ffd3", "postId": postId, "commentName":"\(youProfileName)", "onPost":"45454252342","postOwnerId":"34343434543"

注:您可以根据需要设置以下或以上数据

Firestore.firestore().collection("posts/\(postId)/Comments").addDocument(commentData)
 类似资料:
  • 我有一个类文件Nepokretnost。java中的构造函数如下所示: 此外,我还为每个类字段提供了带有列的TableView。我的问题是双字段“povrsina”。我想从TextField设置它。 我将名为txtPovrsina的TextField的内容发送给双变量: 然后将所有字段放入TableView: 一切都很好,但我想要一些我不知道如何设置的应用程序行为。现在,当我在TextField中

  • 问题内容: 当我从数据库中检索数据时,我碰壁了。我设法将列名放入我的表中,这可以正常工作并且应该工作。 当我尝试添加行时发芽,我发现没有数据添加到我的tableview中,我试图从代表单个行的字符串数组中添加行。我不知道用户会用他的查询请求多少列以及如何大表是这样,所以我不能创建行对象和代表每一列的所有属性。 问题 是如何用从数据库中成功检索到的行填充String表中的行,并以String []的

  • 我有一个类<code>SimpleHistogram 以下是我到目前为止所拥有的: 我正在努力实现函数<code>setCount(DT item,int count)</code>,该函数应该将<code>item</code>的计数设置为<code>count</code>。 另外,如果< code>item在列表中不存在,那么我们应该添加该项,然后将该项的计数设置为< code>count。

  • 问题内容: 我正在使用这些代码在derby数据库中创建表。 我的数据是这样存储的。 但是我希望我的数据像这样存储 我应该如何处理我的数据类型? 问题答案: 使用定义了精度和小数位数的DECIMAL类型: 的代表的允许数目(两个向左和小数POIN的右侧)的总位数,以及表示允许小数的位数。因此,上面的示例定义了一个十进制数字,该数字最多允许5位数字,小数部分为2位数字。

  • 问题内容: 我有1个类文件Nepokretnost.java,其中的构造函数如下所示: 此外,对于每个类字段,我都有带有列的TableView。我的问题是双字段“ povrsina”。我想从TextField设置它。 我将名为txtPovrsina的TextField的内容发送给double变量: 然后将所有字段放在TableView中: 一切运行良好,但是我想要一些应用程序的行为,但我不知道如何

  • 问题内容: 我是Python和Django的新手。 我正在使用PostgreSQL数据库引擎后端配置Django项目,但是每个数据库操作都出现错误。例如,当我跑步时,我得到: 有人可以告诉我发生了什么吗? 问题答案: 你需要安装psycopg2Python库。 安装 下载http://initd.org/psycopg/,然后将其安装在Python PATH下 下载后,轻松解压缩tarball并:

  • 我想在不同的情况下芳香地改变一些约束。 声明来自情节提要的约束: 这是我的代码,我想在其中更改约束: 但是约束仍然没有改变。 这是我的手机ForRowAt func: 提前感谢您的帮助!

  • 我是javafx的新手。我已经在核心java代码设置值表。但是现在我正在转换我的javafx项目来维护代码和改进设计。 我试图设置价值表视图,但我不知道如何设置价值表视图。 这是我用来挥杆的代码。 但我需要将javafx中的代码从JTable转换为TableView。但是tableview没有找到getModel()方法。 我进行了搜索,但没有找到如何设置表视图的值<请给我参考或提示。 提前谢谢。