Swift Firebase:更新Firebase查询产生的特定对象

时间:2016-10-02 17:05:23

标签: ios swift firebase firebase-realtime-database

我的Firebase DB中有以下结构:

Firebase JSON

我希望将具有特定read的所有对象的true属性更新为mealID。我试过这个:

if let selectedIndexPath = tableView.indexPathForSelectedRow {
                meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false
                let mealId = mealIds[(selectedIndexPath as NSIndexPath).row]
                let notificationsRef = ref.child("notifications")
                //get all notifications with this mealId
                var mealNotifications = notificationsRef.queryOrdered(byChild: "mealId").queryEqual(toValue: mealId)
                //notificationRef.updateChildValues(["read":true])
            }

查询正在输出正确的通知对象,我只是不确定如何更新这些特定对象(使用mealNotifications)。有什么想法吗?

修改

我添加了一个observe事件,但是我没有在输出中收到任何对象(我期待单个输出)。我相信这是因为我正在查看通知ID级别,而不是mealID级别。如何在查询中更正此内容?

if let selectedIndexPath = tableView.indexPathForSelectedRow {
                meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false
                let mealId = mealIds[(selectedIndexPath as NSIndexPath).row]
                let notificationsRef = ref.child("notifications")
                //get all notifications with this mealId
                var mealNotifications = notificationsRef.queryOrdered(byChild: "mealId").queryEqual(toValue: mealId).observe(.value, with: {snapshot in
                    print("MEALS:",snapshot)
                    })
                //notificationRef.updateChildValues(["read":true])
            }

1 个答案:

答案 0 :(得分:0)

以下工作:

if let selectedIndexPath = tableView.indexPathForSelectedRow {
                meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false
                let mealId = mealIds[(selectedIndexPath as NSIndexPath).row]
                let notificationsRef = ref.child("notifications")
                //get all notifications with this mealId
                var mealNotifications = notificationsRef.queryOrdered(byChild: "mealID").queryEqual(toValue: mealId).observe(.value, with: {snapshot in
                    let enumerator = snapshot.children
                    while let rest = enumerator.nextObject() as? FIRDataSnapshot {
                        notificationsRef.child(rest.key).child("read").setValue(true)
                        }
                        })
                    tableView.reloadRows(at: [selectedIndexPath], with: .none)
                }