如何快速点击Firestore中的uitablecellviewcell来获取文档ID [英] how to get document id on tapping the uitablecellviewcell in Firestore in swift

查看:28
本文介绍了如何快速点击Firestore中的uitablecellviewcell来获取文档ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击UItableViewCell时应该如何获取文档ID?

How should I get the document id upon tapping the 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

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

帖子模型

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

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

推荐答案

向您的 Post 结构中添加一个新的documentId属性:

Add a new documentId property to your Post struct:

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

更改您的 retrieveAllPosts 函数并设置Post实例的documentId,请不要为此使用全局变量:

Change your retrieveAllPosts function and set the documentId of the Post instance, do not use the global variable for this:

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

现在,您可以在didSelectRowAt中访问所选 Post 的documentId:

Now you can access the documentId of the selected Post in didSelectRowAt:

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.

这篇关于如何快速点击Firestore中的uitablecellviewcell来获取文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆