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

3 ios firebase swift google-cloud-firestore

我想从 firestore 获取文档的 id 并将它们存储在一个变量中以在下一页中使用。

我怎样才能快速做到这一点?我尝试了这种方法,但它生成一个随机 ID,而不是我拥有的集合的特定文档 ID

let docRef = Firestore.firestore().collection("Shops").document()
let docId = docRef.documentID
Run Code Online (Sandbox Code Playgroud)

附件是我需要在变量中检索的文档 ID。

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

小智 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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)