Ios 检索Firestore集合数据-错误-隐式展开可选值时意外发现nil
当我试图从collection->document id->field中获取数据时,我一直在使用Firestore来检索数据。参考下面的屏幕截图,我需要检查companyCode与用户输入的companyCode.text的匹配情况 我尝试使用以下代码,需要检查用户输入的companyCodeLabel.text是否与文档“companyCode”匹配,并获取documentId。有人能建议如何解决这个问题吗Ios 检索Firestore集合数据-错误-隐式展开可选值时意外发现nil,ios,swift,firebase,google-cloud-firestore,Ios,Swift,Firebase,Google Cloud Firestore,当我试图从collection->document id->field中获取数据时,我一直在使用Firestore来检索数据。参考下面的屏幕截图,我需要检查companyCode与用户输入的companyCode.text的匹配情况 我尝试使用以下代码,需要检查用户输入的companyCodeLabel.text是否与文档“companyCode”匹配,并获取documentId。有人能建议如何解决这个问题吗 guard let code = companyCodeLabel.text el
guard let code = companyCodeLabel.text else { return }
let docRef = db.collection("Company").whereField("companyCode", isEqualTo: code).limit(to: 1)
docRef.getDocuments { (querysnapshot, error) in
if error != nil {
print("Document Error: ", error!)
} else {
if let doc = querysnapshot?.documents, !doc.isEmpty {
print("Document is present.")
}
}
}
甚至尝试打印集合中的字段值,但仍然出现崩溃和相同的错误nil
self.db.collection("Company").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let docId = document.documentID
let compCode = document.get("companyCode") as! String
let compName = document.get("companyName") as! String
print(docId, compCode, compName)
}
}
}
我试图调用错误的数据库,我正在尝试
var db=Firestore代码>,
正确的解决方案是
Firestore.firestore().collection("Company").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let docId = document.documentID
let compCode = document.get("companyCode") as! String
let compName = document.get("companyName") as! String
print(docId, compCode, compName)
}
}
调试代码。设置断点。看电视。document
是否包含您期望的内容?@vadian它在上述两个代码的第一行立即崩溃。再次:调试您的代码。您是说它在这一行崩溃吗guard let code=companycodelab.text else{return}
,因为这是第一行。什么是self.db
还是仅仅db
。你能给我们看一下在XCode中出现的错误消息吗?包括它崩溃的那一行吗?@Jay崩溃不是来自guard let code=…text,,,,,,,let db=Firestore!,崩溃是从两个代码的第一行开始的db.collection。。。崩溃消息是线程1:致命错误:隐式展开可选值时意外发现nil