简体   繁体   English

如何快速在Firestore中点击uitablecellviewcell来获取文档ID

[英]how to get document id on tapping the uitablecellviewcell in Firestore in swift

How should I get the document id upon tapping the UItableViewCell? 点击UItableViewCell时应如何获取文档ID?

I know the below code do give me the row index, but for a feed post I would like to get the document id for the the particular post everytime 我知道下面的代码确实给了我行索引,但是对于提要帖子,我想每次都获取特定帖子的文档ID

I have tried to retrieve the document id through key setup in model file but avail to no good 我试图通过模型文件中的密钥设置来检索文档ID,但没有用

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("row selected: \(indexPath.row)")
        performSegue(withIdentifier: "toDetailView", sender: indexPath)
    }

Posts Model 帖子模型

import Foundation
import Firebase
import FirebaseFirestore


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


struct Post {

     var _username: String!
     var _postTitle: String!
     var _postcategory:  String!
     var _postContent:  String!




    var dictionary:[String:Any] {
        return [
            "username": _username,
            //"profile_pic":profile_pic,
            "postTitle":_postTitle,
            "postcategory":_postcategory,
            "postContent":_postContent
                   ]
    }

}

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 }


        self.init( _username: username ,_postTitle: postTitle, _postcategory: postcategory, _postContent: postContent)

    }
}

Code to retrieve the collection as whole into. 检索整个集合的代码。 tableview 的tableview

import Foundation
import UIKit
import Firebase


class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

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

    var postKey:String = ""
    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()
        //checkForUpdates()

    }


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


   /* override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        performSegueWithIdentifier("toDetailPage", sender: indexPath)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let indexPath = self.tableView.indexPathForSelectedRow
        let person = personList[indexPath!.row]

        if segue.identifier == "toDetailPage"{
            let DetailBookViewController = (segue.destinationViewController as! DetailPage)
            DetailBookViewController.user_name = user_name
            DetailBookViewController.user_age = user_age
            DetailBookViewController.user_urlPicture = user_urlPicture

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

    /*func checkForUpdates() {
        db.collection("posts").whereField("timeStamp", isGreaterThan: Date())
            .addSnapshotListener {
                querySnapshot, error in

                guard let snapshot = querySnapshot else {return}

                snapshot.documentChanges.forEach {
                    diff in

                    if diff.type == .added {
                        self.posts.append(Post(dictionary: diff.document.data())!)
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }

        }
    }*/

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

        postsRef.getDocuments { (snapshot, error) in

            if let error = error {

                print(error.localizedDescription)

            } else {

                if let snapshot = snapshot {

                    for document in snapshot.documents {


                        let data = document.data()
                        self.postKey = document.documentID
                        let username = data["username"] as? String ?? ""
                        let postTitle = data["postTitle"] as? String ?? ""
                        let postcategory = data["postcategory"] as? String ?? ""
                        let postContent = data["postContent"] as? String ?? ""

                        let newSourse = Post(_postKey:self.postKey, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent)
                        self.posts.append(newSourse)
                        print(self.postKey)
                    }
                    self.tableView.reloadData()
                }
            }
        }
    }

       /* 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
    }

     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("row selected: \(indexPath.row)")

        //performSegue(withIdentifier: "toDetailView", sender: indexPath)
    }
}

Add a new documentId property to your Post struct: 向您的Post结构添加一个新的documentId属性:

struct Post {
    var _username: String!
    var _postTitle: String!
    var _postcategory:  String!
    var _postContent:  String!
    var _documentId: String! // This is new.

    var dictionary:[String : Any] {
        return [
            "documentId" : _documentId, // This is new.
            "username": _username,
            //"profile_pic":profile_pic,
            "postTitle":_postTitle,
            "postcategory":_postcategory,
            "postContent":_postContent
        ]
    }
}

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 documentId = dictionary["documentId"] as? String // This is new.
            let postContent = dictionary["postContent"] as? String   else { return nil }

            self.init( _username: username ,_postTitle: postTitle, _postcategory: postcategory, _postContent: postContent, _documentId: documentId)
    }
}

Change your retrieveAllPosts function and set the documentId of the Post instance, do not use the global variable for this: 更改您的retrieveAllPosts函数并设置Post实例的documentId,请勿为此使用全局变量:

if let snapshot = snapshot
{
    for document in snapshot.documents
    {
        let data = document.data()
        let username = data["username"] as? String ?? ""
        let postTitle = data["postTitle"] as? String ?? ""
        let postcategory = data["postcategory"] as? String ?? ""
        let postContent = data["postContent"] as? String ?? ""

        let newSourse = Post(_postKey:self.postKey, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent, _documentId: document.documentId)
        self.posts.append(newSourse)
    }
}

Now you can access the documentId of the selected Post in didSelectRowAt: 现在,您可以在didSelectRowAt中访问所选Post的documentId:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let post = self.posts[indexPath.row]
    Swift.print(post.documentId)

    // print("row selected: \(indexPath.row)")
    // performSegue(withIdentifier: "toDetailView", sender: indexPath)
}

Hopefully this will guide you into the right direction. 希望这将引导您走向正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM