如何使用Swift从Firestore集合中获取文档ID?

3
我想从Firestore获取文档的ID并将它们存储在一个变量中,以便在我的下一页中使用。
如何用Swift实现这个功能?我尝试了这种方法,但它生成的是随机ID,而不是我所拥有的集合中特定文档的ID。
let docRef = Firestore.firestore().collection("Shops").document()
let docId = docRef.documentID

这里是我需要在变量中检索的文档ID。

这些是我需要在变量中检索的ID

1个回答

6
你可以使用getDocuments()获取集合中的所有文档,或使用.addSnapshotListener()自动获取新文档。
Firestore.firestore().collection("Shops").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID)") // Get documentID
            print("\(document.data)") // Get all data
            print("\(document.data()["name"] as! String)") // Get specific data & type cast it.
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接