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

时间:2019-08-30 08:02:38

标签: ios swift firebase uitableview google-cloud-firestore

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

我知道以下代码确实为我提供了行索引,但是对于提要帖子,我希望每次都获取特定帖子的文档ID

我试图通过模型文件中的密钥设置来检索文档ID,但无济于事

require 'file.php'

帖子模型

require_once 'my_funcs.php'

将整个集合检索到的代码。表格视图

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

1 个答案:

答案 0 :(得分:1)

向您的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)
    }
}

更改您的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)
    }
}

现在,您可以在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)
}

希望这会引导您走向正确的方向。