ios - 使用 queryOrdered by date 对 Firebase 数据进行排序

标签 ios swift firebase firebase-realtime-database

我需要按日期 (unix) 排列我的 firebase 数据。我认为 queryOrdered(byChild: "date") 可以解决问题。完成了 search并找到this这是有道理的:

But when you request the .value of the snapshot, the keys+data are converted to a Dictionary. Since a dictionary does not have an extra place to put the information about the order, that information is lost when converting to a dictionary.

使用相同的 json 但用 unix 日期修改...:

{
  "users" : {
    "alovelace" : {
      "name" : "Last Year",
      "date" : 1480550400
    },
    "eclarke" : {
      "name" : "New Year Now",
      "date" : 1483228800
    },
    "ghopper" : {
      "name" : "New Year",
      "date" : 1483228800
    }
  }
}

...当我的代码是这样的时候如何排序:

DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in

    if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
        print(snapshot)
        for snap in snapshot {
            if let incomeDict = snap.value as? [String: AnyObject] { // What needs to change here?
                let key = snap.key
                let income = Income(incomeId: key, incomeData: incomeDict)
                self.incomes.append(income)
                self.incomes.reverse()
            }
        }
    }
    self.tableView.reloadData()
})

下图,“去年”应该是最后但不是:

enter image description here

我有一个 ruby mentality所以我很快就迷路了。谢谢。

最佳答案

我想你在这里缺少的是 sort 功能,请尝试下面的代码,让我知道结果是什么:

DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in

    guard let usersSnapshot = snapshot.value as? [String:NSObject] else{

        return
    }

    let users = usersSnapshot["users"] as! [String:AnyObject]
    let sorted = users.sorted{($0.0.value["date"] as! Double) > ($0.1.value["date"] as! Double)}


    print(sorted) // It should be: New Year Now, New Year, Last Year
})

关于ios - 使用 queryOrdered by date 对 Firebase 数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416359/

相关文章:

ios - UISearchController 需要额外点击才能成为第一响应者

ios - UICollectionViewCell 在 UICollectionViewReusableView 宽度之后启动

ios - 快速在表格 View 中插入单元格

javascript - 添加数据时如何向下滚动到页面底部?

node.js - 如何仅使用firebase进行身份验证并使用nodejs作为后端?

ios - 在 UIImagePicker Controller 上提供选区,单独抓取选区?

ios - 如何在 Xcode Storyboard中为我的 iPhone 应用程序的设置创建 View

ios - 当 iOS 设备插入电源时唤醒应用程序

ios - 滚动内的 UITableView,UINavigationController 内不能 pushViewController

ios - 跨 iOS 设备保持 Firebase 身份验证状态