将文档引用传递给第二个视图控制器

时间:2018-05-07 16:14:52

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

有人可以告诉我如何制作它,这样当我点击tableView中的特定行时,文档引用会传递给第二个ViewController,允许我显示子集“Friends”中的字段。目前我可以这样做但不使用autoID。请问某人如何使用autoID做到这一点?非常感谢任何帮助,非常感谢!!

Current Firebase Console

What I would like - Firebase Console

First ViewController

    func loadData() {
    db.collection("Users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let data = document.data()
                let name = data["name"] as? String ?? ""
                let newName = UsersNames(name: name)
                self.nameArray.append(newName)
            }
            self.tableView.reloadData()
        }
    }
}

第二个ViewController

    func loadData() {
    db.collection("Users").document("Hello").collection("Friends").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let data = document.data()
                let name = data["name"] as? String ?? ""
                let details = data["details"] as? String ?? ""
                let newFriends = Friends(friendName: name, friendDetails: details)
                self.friendsArray.append(newFriends)
            }
            self.tableView.reloadData()
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您想这样做,首先需要向UsersNames对象添加documentID属性:

    struct UsersNames {

        var documentID: String //<-- Add this
        var name: String
    }

然后更新您的第一个VC中的loadData()功能,以获取每个documentID文档中的Firestore并附加到您的Array

        for document in querySnapshot!.documents {
            let data = document.data()
            let documentID = document.documentID //<-- Add this
            let name = data["name"] as? String ?? ""
            let newName = UsersNames(documentID: documentID, name: name) //<-- Change this
            self.nameArray.append(newName)
        }

在第一个VC中,您希望在选择单元格时对第二个VC执行Segue,并将documentID中所选对象的Array传递给第二个VC

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "SecondVC", sender: self)
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let indexPath = tableView.indexPathForSelectedRow {
            let destinationVC = segue.destination as! SecondVC
            let documentId = nameArray[indexPath.row].documentID
            destinationVC.documentID = documentID
        }
    }

在SecondVC中创建一个属性以接收documentID:

    var documentID: String!

在SecondVC loadData()函数中,您现在可以访问从第一个VC传递的documentID:

    db.collection("Users").document(documentID).collection("Friends").getDocuments() { //..