ios - Swift 检索 Firebase 数据

标签 ios swift firebase swift3 firebase-realtime-database

Firebase 数据库中的以下数据:

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

我想检索仅事件为 true 的所有周。 我将 Firebase 引用设置如下:

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

然后执行以下操作:

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

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

    })

产生以下输出:

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

有人可以建议我如何获取 active 设置为 true 且需要加载到字符串类型数组中的周数吗:

var weeksActive = [String]()

最佳答案

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

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

关于ios - Swift 检索 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719620/

相关文章:

iOS webview 缩放以匹配视网膜显示

iphone - AVAssetReader 读取视频样本的基本问题

ios - 第一个从计时器完成后如何在下面的函数中调用函数

firebase - 单击推送通知时如何在我的 flutter 应用程序中打开特定页面

java - 如何从 Firestore 查询中排除元素?

javascript - Firebase Cloud Functions 托管, 'once' 回调在云函数中有效,但在托管站点中无效

ios - wireguard ios,路由 ip+net : sysctl: operation not supported

ios - 围绕 anchor 旋转 UIImageView

swift - NSPredicate 用于过滤 Realm 3 中的原始字段数组

ios - 在同一个 UIViewController 中使用 NavigationDrawerController 和 ToolbarController