在我的应用程序中,我使用的是折扣代码,这将检查内容:
是否存在折扣代码,但已经使用了。
db.collection("discountCode").whereField("discountID", isEqualTo: txtfield_discountCode.text!).getDocuments(completion: { (query, err) in
if let err = err{
print(err.localizedDescription)
}
else{
for documents in query!.documents{
let data = documents.data()
let discountCode = data["discountID"] as? String
let percent = data["percent"] as? String
let category = data["category"] as? String
let expiring = data["expiring"] as? String
self.checkIfCodeExists(discountCode: discountCode, percent: percent, category: category, expiring: expiring)
}
}
})
但是,即使没有任何文档,其中“ discountID”等于“ txtfield_discountCode.text”,该代码也将始终执行“ else-statement”
我是否可以检查是否找到与文本字段相同的字段?
我试图这样做:
if query!.documents == nil{ print("Code could not be found")}
但这不起作用。
所以无论如何,我可以检查“ .wherefield”是否未找到任何文档吗?
答案 0 :(得分:3)
问题是您没有错误,只是从数据库中获取了空列表。另外,您应该安全地打开选装件。
您需要这样的东西:
guard let validCode = txtfield_discountCode.text else {
print("code not entered")
return
}
db.collection("discountCode").whereField("discountID", isEqualTo: validCode).getDocuments(completion: { (query, err) in
if let err = err {
print(err.localizedDescription)
} else {
if let validQuery = query, !validQuery.documents.isEmpty {
for documents in validQuery.documents {
let data = documents.data()
let discountCode = data["discountID"] as? String
let percent = data["percent"] as? String
let category = data["category"] as? String
let expiring = data["expiring"] as? String
self.checkIfCodeExists(discountCode: discountCode, percent: percent, category: category, expiring: expiring)
}
} else {
print("Document not found")
}
}
}