Swift Retreive Firebase数据 [英] Swift Retreive Firebase data

查看:117
本文介绍了Swift Retreive Firebase数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase数据库中的以下数据:

  {
schedule:{
第2周:{
active:true
},
Week 2:{
active:true
},
Week 3:{
active:false
},
Week 4:{
active:true
},
...
}
}

I想要检索只有活动状态为真的所有星期。
我将Firebase参考设置为:

  ref = FIRDatabase.database()。reference(withPath:附表)

然后执行以下操作:



print(Count:,snapshot.childrenCount)

for _ in snapshot.children {
print(\(snapshot.value))
}

})

产生以下输出:

 可选({
Week 1= {
active = 1;
};
Week 2= {
active = 1; $ b $第3周= {
活动= 0;
};
第4周= {
活动= 1;
} ;
...
}

只是几个星期重新激活被设置为真正需要被加载到一个字符串类型的数组:

  var weeksActive = [String]() 


解决方案

为此,您可以使用 queryOrdered(byChild:) queryEqual(toValue:)就像这样。

<$ p $ ():$ {code> let ref = FIRDatabase.database()。reference(withPath:Schedule)。queryOrdered(byChild:active)。queryEqual(toValue:true)

ref .observe(.value,在
$ b $ print(Count:,snapshot.childrenCount)中的{(快照)$为快照.children中的子
{
print( \\((孩子当! (FIRDataSnapshot.value))
//得到星期,你需要访问键
print(\((child as!FIRDataSnapshot).key))
}
})


The following data in the Firebase Database:

{
  "schedule": {
      "Week 1": {
        "active": "true"
      },
      "Week 2": {
        "active": "true"
      },
      "Week 3": {
        "active": "false"
      },
      "Week 4": {
        "active": "true"
      },  
      ...
   }
}

I want to retrieve all the Weeks where the active is true only. I am setting the Firebase reference as such:

ref = FIRDatabase.database().reference(withPath: "Schedule")

and then doing the following:

ref.observeSingleEvent(of: .value, with: { snapshot in
        //
        print("Count: ", snapshot.childrenCount)

        for _ in snapshot.children {
                print("\(snapshot.value)")
        }

    })

Which produces the following output:

Optional({
      "Week 1" =     {
           active = 1;
       };
       "Week 2" =     {
           active = 1;
       };
       "Week 3" =     {
           active = 0;
       };
       "Week 4" =     {
           active = 1;
       };
       ...
}

Can someone please suggest how I can get just the weeks where active is set to true which needs to be loaded in an array of type string :

var weeksActive = [String]()

解决方案

For that you can use queryOrdered(byChild:) and queryEqual(toValue:) like this.

let ref = FIRDatabase.database().reference(withPath: "Schedule").queryOrdered(byChild: "active").queryEqual(toValue : true)

ref.observe(.value, with:{ (snapshot) in

    print("Count: ", snapshot.childrenCount)
    for child in snapshot.children {
        print("\((child as! FIRDataSnapshot).value)")
        //To get week you need to access key
        print("\((child as! FIRDataSnapshot).key)")
    }
})

这篇关于Swift Retreive Firebase数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆