首页 > 解决方案 > 如何使用 Firestore 数据库在 swift 中为 tableview 中的项目列表设置 postkey?

问题描述

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

从昨天开始我尝试了很多东西,但都没有用。我需要使用 postkey 在帖子上发布评论。

在我正在关注的代码下方

发布模型 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
    }
}

标签: iosswiftdatabasefirebasegoogle-cloud-firestore

解决方案


这不是一个简单的帖子键,您需要在该列表中创建名为“comments”的帖子的子文档,您需要添加commentContent、byUser、toUser、onPost等。仅添加 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)

对于击球手的理解,您可能会看到下面的房间示例

如何将子集合添加到 Firebase Cloud Firestore 中的文档


推荐阅读