2

How to setup the postkey for the list of items in the tableview in swift using Firestore database?

I tried lots of stuff since yesterday but avail to no good. I need to use the postkey for posting the comments on the post.

Below the code which is I am following

Post Model Swift File

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 )
    }
}

ViewController class used to enlist the posts in tableview

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
    }
}
Constantin Beer
  • 5,447
  • 6
  • 25
  • 43
  • show us sample response too :) – Abu Ul Hassan Aug 29 '19 at 06:33
  • in response the table view is filled with the respective elements of each post item you can see any general response.... for commenting purpose I need to have the post key so that the comment can go to the particular post chosen by the user. –  Aug 29 '19 at 06:41
  • it will not be a simple post key you will be in need to create sub document of post likes named "comments" in that list you will be in need to add commentContent, byUser, toUser, onPost etc . adding just postKey will not solve your problem – Abu Ul Hassan Aug 29 '19 at 06:46
  • thank you for the guidance, is there any similar example available online? –  Aug 29 '19 at 06:54
  • i think its in my personal MAC and right now i am at office MAC – Abu Ul Hassan Aug 29 '19 at 06:59
  • no worries I will wait for it, thanks –  Aug 29 '19 at 07:01
  • answered... below – Abu Ul Hassan Aug 29 '19 at 07:11

1 Answers1

0

it will not be a simple post key you will be in need to create sub document of post likes named "comments" in that list you will be in need to add commentContent, byUser, toUser, onPost etc . adding just postKey will not solve your problem

Here you go for simple example

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

Note: you may set below or above data according to your need

Firestore.firestore().collection("posts/\(postId)/Comments").addDocument(commentData)

for a batter understanding you may see rooms example below

How to add subcollection to a document in Firebase Cloud Firestore

Abu Ul Hassan
  • 1,340
  • 11
  • 28