In my application I'm using discount codes, and this is going to check to things:
If the discount code exists but is already used.
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)
}
}
})
But the code will always run to the "else-statement" even if no documents where "discountID" is equal to "txtfield_discountCode.text"
Is there anyway I can check if no fields is found that's equal to the textfield?
I've tried to do like this:
if query!.documents == nil{ print("Code could not be found")}
But that does not work.
So is there anyway I can check if ".wherefield" did not found any documents?
The problem is that you don't have an error, you are just getting empty list from the database. Also you should safely unwrap your optionals.
You need something like this:
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")
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments