Swift Firebase:查询没有父键的子节点

时间:2017-02-19 13:50:18

标签: ios swift firebase firebase-realtime-database

好的我有以下结构,我想拉出包含注册信息的所有节点。

{
  "events" : {
    "hsoigjpoirt94pwjfjoijfdg" : {
      "coverImageURL" : "http://www.who.int/about/Logo-WHO.jpg",
      "dateTime" : "22 May, 2pm",
      "eventDescription" : "Lorem ipsum ...",
      "eventID" : "hsoigjpoirt94pwjfjoijfdg",
      "lat" : 1.2945,
      "lon" : 103.8822,
      "registered" : {
        "NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true
      },
      "title" : "Volunteer at WHO"
    },
    "hvasdhpoifah98whfaksad" : {
      "coverImageURL" : "http://s3.amazonaws.com/patientslikeme/organizations/11/NKF_D_NEWE_RGB-original.png?1317242994",
      "dateTime" : "24 July, 2:30pm",
      "eventDescription" : "Lorem ipsum ...",
      "eventID" : "hvasdhpoifah98whfaksad",
      "lat" : 1.432079,
      "lon" : 103.836871,
      "registered" : {
        "NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true
      },
      "title" : "Help at Yishun Dialysis"
    },
    "jioasdifueivaf5262d" : {
      "coverImageURL" : "http://www.publichygienecouncil.sg/images/default-source/Photo-Galleries/walk-for-your-kidneys-by-nkf/nkf-litter-picking_25-jan-2014.jpg?sfvrsn=6",
      "dateTime" : "12 Feb, 3-6pm",
      "eventDescription" : "Lorem ipsum  ...",
      "eventID" : "jioasdifueivaf5262d",
      "lat" : 1.33831,
      "lon" : 103.705326,
      "title" : "Charity Concert at NKF"
    }
  },
}

我想用密钥"NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true提取包含“已注册”的所有快照。到目前为止,我尝试了以下内容,但是它可以解决所有问题:

ref.child("events").queryOrdered(byChild: "registered").observe(.value, with: { (snapshot) in

            let snapValues = snapshot.value as! [String: AnyObject]

            print(snapValues)                

        }) { (error) in
            print(error.localizedDescription)
        }

仅供参考,这些节点中的每一个都是个人可以注册到事件的事件。我想创建一个列出特定用户已注册的所有事件的视图。

1 个答案:

答案 0 :(得分:1)

是的,就在我即将放弃的时候,我设法找到了一个解决方案来获得我想要的快照。以下是我如何去做的事情:

ref.child("events").queryOrdered(byChild: "registered").observe(.value, with: { (snapshot) in

            for snap in snapshot.children {
                let snapDataSnapshot = snap as! FIRDataSnapshot
                let snapValues = snapDataSnapshot.value as? [String: AnyObject]

                if let snapWithReg = snapValues?["registered"] as? [String: Bool] {

                    if snapWithReg[userUID]! {
                        print(snap)
                    }
                }
            }


        }) { (error) in
            print(error.localizedDescription)

        }

快照与“已注册”的快照完全相同。节点和userUID "NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true