ios - 让条件在 Firebase Observer 中工作

标签 ios swift firebase firebase-realtime-database

我正在尝试在 Firebase Observer 中执行条件操作。 本质上我喜欢检查座位是否被占用。 如果是,则可以检索订单。 如果没有,则再次将餐厅发送回搜索座位页面。 由于某种原因,即使满足条件(即车主输入了错误的座位号),if !taken 中的代码也永远不会执行。我已经把它放在闭包中了,它应该运行吧?

func retrieveData (){
    var taken = false
    var seatNumber = "**an Int from other page**"
    let refCustomer = Database.database().reference().child("Restaurant").child("Customers")
        refCustomer.queryOrdered(byChild: "Seat").queryEqual(toValue: "\(seatNumber)").observeSingleEvent(of: .childAdded, with: { (snapshot) in
            if snapshot.exists() {
                taken = true
                let snapshotValue = snapshot.value as? [String : AnyObject] ?? [:]
                self.customerFirstName = snapshotValue["Firstname"] as! String
                self.customerLastName = snapshotValue["Lastname"] as! String
                self.customerAllergy = snapshotValue["Allergy"] as! String
                self.customerID = snapshot.key
                self.allergy.text = self.customerAllergy
                self.ptname.text = "\(self.customerFirstName) \(self.customerLastName)"
            }
            if !taken {
                print ("oops")
                self.performSegue(withIdentifier: "MainPage", sender: self)
            }
        })
    }

最佳答案

这段代码有很多问题,可能还有你的结构,所以让我看看是否可以为你指出正确的方向。

首先,您可以删除不需要的变量。简而言之

if snapshot.exists() {
   //handle the snapshot
} else {   //use else here as if the snapshot doesn't exist we want this code to run
   print ("oops")
}

第二,确保你的结构是这样的

Customers
  cust_0
    Seat: 1
  cust_1
    Seat: 2

等等

第三,这是一串“1”

queryEqual(toValue: "\(seatNumber)")

并且你想查询一个 Int,所以就这样做

queryEqual(toValue: seatNumber)

查询 Int 为 1

第四:

查询 Firebase 时,如果 .childAdded 找不到任何内容,则不会执行闭包。您应该使用.value。

来自 .childAdded 的文档

This event is triggered once for each existing child and then again every time a new child is added to the specified path.

因此,如果没有子节点与查询匹配,则不会执行。

使用这个

refCustomer.queryOrdered(byChild: "Seat")
           .queryEqual(toValue: seatNumber)
           .observeSingleEvent(of: .value, with: { (snapshot) in

而且...这是重要的部分,.value 检索与查询匹配的所有节点,因此您需要迭代这些节点才能使用子节点。假设只有一场比赛,那么你可以这样做

guard let allChildren = snapshot.children.allObjects as? [DataSnapshot] else {return}
let firstChild = allChildren.first

第五。虽然从技术上讲这是可以的

let f = snapshotValue["Firstname"] as! String

您保证 Firstname 节点始终存在。如果这是真的,那就随它去吧。然而,更安全、更 swift 方法是这样做

let f = snapshotValue["Firstname"] as? String ?? "No First Name"

关于ios - 让条件在 Firebase Observer 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136526/

相关文章:

ios - UIPageViewController 中的动画

ios - 保存一对多关系CoreData

ios - 从 Swift 3 中的锁屏清除本地通知

firebase - 使用 rxDart 合并 Firestore 流

javascript - Firestore 网络无法到达 Firestore 后端

iOS CoreLocation 没有获取 GPS 坐标

iOS UITableView 隐藏表头空间

node.js - Cloud Functions for Firebase 性能

swift - 快速编辑具有约束的多个文本字段时移动键盘

ios - 如何从 Swift 中的容器 View 获取属性值