[英]How do i get firestore document id in a generic method?
i am new to swift and i am trying to implement generic method to fetch data from firestore.我是 swift 的新手,我正在尝试实现从 Firestore 获取数据的通用方法。
func fetch<T: Codable>(query: Query, completion:@escaping (Result<[T]?, Swift.Error>) -> Void) {
var dataArray = [T]()
query.addSnapshotListener { (querySnapshot, error) in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
completion(.failure(error!))
return
}
if snapshot.isEmpty {
completion(.success(nil))
return
}
snapshot.documentChanges.forEach { change in
var data: T!
do {
data = try FirestoreDecoder().decode(T.self, from: change.document.data())
} catch let error {
completion(.failure(error))
return
}
if (change.type == .added) {
// print("New data: \(change.document.data())")
dataArray.append(data)
}
}
completion(.success(dataArray))
}
but here i don't know how do i get the document id from change.document.data().但在这里我不知道如何从 change.document.data() 获取文档 ID。 please help me out if any one knows.如果有人知道,请帮助我。 thank you.谢谢你。
Maybe these links can help https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/DocumentChange也许这些链接可以帮助https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/DocumentChange
https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/QueryDocumentSnapshot https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/QueryDocumentSnapshot
You have the property newIndex in change of type UInt or you can print the content of change.document.data() and see if there is a field with a name corresponding to an id.你有属性 newIndex in change 类型 UInt 或者你可以打印 change.document.data() 的内容,看看是否有一个名称对应于 id 的字段。 The data method contains the values of a document on your firestore console. data 方法包含 Firestore 控制台上文档的值。
Then you can access the dictionary item as follows:然后您可以按如下方式访问字典项:
change.document().data()["id"] as? Int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.