ios - 如果找不到 whereField

标签 ios swift google-cloud-firestore

在我的应用程序中,我使用了折扣代码,这将检查以下内容:

  • 如果折扣码存在
  • 如果折扣码存在但已被使用。

        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”

无论如何我可以检查是否没有找到与文本字段相等的字段?

我试过这样做:

  • (在 else 的开头)-> if query!.documents == nil{ print("找不到代码")}

但这不起作用。

那么有没有办法检查“.wherefield”是否没有找到任何文件?

最佳答案

问题是您没有错误,您只是从数据库中获取空列表。你也应该安全地打开你的选项。

你需要这样的东西:

    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")
            }
        }
    }

关于ios - 如果找不到 whereField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303580/

相关文章:

class - swift 有类级别的静态变量吗?

java - 在android中添加新数据时ArrayList数据被清除

ios - "NSInternalInconsistencyException [...] Sigh. Contentview size is zero."使用 UINavigationController 时崩溃

ios - 在横向屏幕上旋转不是 iPhone 5 和 iPhone 6 上的 View

iphone - 如何将 2 张图像合并/合并为 1 张

flutter - flutter :在 Debug模式下构建时,运行pod安装将永远花费

firebase - Firestore 集合组查询解决方案?

iOS 表情符号在 UILabel 中搞砸了

objective-c - 使用 UICollectionView 构建月/周日历

arrays - 无法将类型 '[[String : AnyObject]]' 的值分配给类型 '[[String : AnyObject?]]'