如何获取Firebase Firestore中随机生成的无唯一标识Document ID
问题描述
各位晚上好,我正在使用Firebase Firestore开发我的毕业设计项目。到目前为止所有功能运行正常,创建用户文档时我使用了document(uid)的方式,但我创建的请求文档情况如下所示:
该场景下的documentID是随机生成的,因为用户可以发起多个请求,所以documentID不能和UID一致。现在我遇到的问题是:用户收到请求后要进行同意/拒绝操作,我当前使用的代码如下:
let TrashAction = UIContextualAction(style: .normal, title: "Decline", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in let dbCollection = K.FStore.db.collection(K.FStore.RequestTransmission.collectionName).document("RDvjapleBC7TBBQ15NE9") dbCollection.updateData([ K.FStore.RequestTransmission.isDeclined : true ]){ err in if let err = err { print("Error updating document: \(err)") } else { print("Document successfully updated") DispatchQueue.main.async { self.tableView.reloadData() } } } success(true) }) TrashAction.backgroundColor = .red
我想要替换代码中硬编码的DocumentID,也就是此处的K.FStore.db.collection(K.FStore.RequestTransmission.collectionName).document("RDvjapleBC7TBBQ15NE9")
请问该如何实现?
解决方案
核心思路是将每个请求对应的文档ID提前存储到UITableView的数据源模型中,操作时直接从当前行对应的模型取值即可,具体实现步骤如下:
- 给请求数据模型新增
documentId字段,用来存储Firestore自动生成的文档ID
struct RequestModel { // 原有业务字段(比如发送方ID、请求内容、是否同意等) let documentId: String }
- 拉取请求列表数据时,同步把文档ID存入模型
// 请求列表拉取逻辑示例 let requestCol = K.FStore.db.collection(K.FStore.RequestTransmission.collectionName) requestCol.getDocuments { [weak self] snapshot, error in guard let self = self, let docs = snapshot?.documents, error == nil else { print(error ?? "拉取请求失败") return } var tempList = [RequestModel]() docs.forEach { doc in let data = doc.data() // 此处解析其他业务字段后初始化模型 let model = RequestModel( // 其他字段赋值 documentId: doc.documentID ) tempList.append(model) } self.requestList = tempList // requestList为UITableView的数据源数组 DispatchQueue.main.async { self.tableView.reloadData() } }
- 构造行滑动操作时,通过当前行的indexPath拿到对应模型的
documentId替换硬编码
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // 拿到当前行对应的请求模型 let currentReq = requestList[indexPath.row] let declineAction = UIContextualAction(style: .normal, title: "拒绝", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // 直接使用模型中存储的文档ID let targetDoc = K.FStore.db.collection(K.FStore.RequestTransmission.collectionName).document(currentReq.documentId) targetDoc.updateData([ K.FStore.RequestTransmission.isDeclined : true ]){ err in if let err = err { print("更新文档失败: \(err)") } else { print("文档更新成功") // 只刷新当前行提升性能 DispatchQueue.main.async { self.requestList[indexPath.row].isDeclined = true self.tableView.reloadRows(at: [indexPath], with: .automatic) } } } success(true) }) declineAction.backgroundColor = .red return UISwipeActionsConfiguration(actions: [declineAction]) }
内容的提问来源于stack exchange,提问作者mohamad
相关产品推荐
相关产品推荐

