Firebase:将过滤与swift中的排序相结合

时间:2015-06-09 16:22:06

标签: swift filter firebase

所以我有一个运动应用程序,处理比赛和锦标赛数据。 我有两个使用相同数据的显示器:

  • 所有未来的比赛
  • 来自某个冠军的所有未来比赛

数据结构如下

- championships
    - libertadores
        - name: Libertadores da América
- matches
    - 2j6g42kjhg62
        - champ: libertadores
        - time: 1433962855
        - <data> //teams, scores, stadium and so on

现在,展示未来的比赛很简单:

matchesRef.queryOrderedByChild("time").queryStartingAtValue(currentTimestamp)
            .queryLimitedToFirst(20)
            .observeEventType(.ChildAdded, withBlock: { (snapshot) in
                // code
            })

但是,因为你不能使用多个queryOrderedByChild,所以我坚持将其与锦标赛的过滤相结合。

我考虑过更改我的数据结构以支持/championship/matches/<matchID>这样的内容,但这会让我很难显示所有未来的匹配。

此处不选择过滤器,那么如何才能达到预期效果?

2 个答案:

答案 0 :(得分:3)

知道了!

在发布问题之前,我已经阅读了文档,但没有点击该信息引导我找到解决方案。

关于结构化数据的这一部分包含答案:https://www.firebase.com/docs/ios/guide/structuring-data.html

理解: 自然结构将是:

 - champs
    - champID
        - matches
            - matchID
            - <matchData>
        - champName

但是,要使用firebase,我们需要规范化数据:

- champs
    - champID
        - champName

- matches
    - matchID
        - champID
        - timestamp
        - <matchData>

我开始提问的结构是什么。

然而,由于锦标赛有比赛和比赛属于锦标赛,我们需要交叉参考他们两个。上面链接的文档告诉我们可以给键值true,因为我们对键的值不感兴趣,只是它存在。但是,因为我只需要将来的匹配,所以解决方案是将匹配时间戳放在值中。

- champs
    - champID
        - matches
            - matchID: timestamp
        - champName
- matches
    - matchID
        - champID
        - timestamp
        - <matchdata>

现在最后的代码:

非过滤视图:

// Query non-filtered matches Reference
matchesRef.queryOrderedByChild("time").queryStartingAtValue(currentTimestamp)
    .queryLimitedToFirst(20).observeEventType(.ChildAdded, withBlock: { (snapshot) in
            // code
    })

过滤后的观点:

// Query filtered matches
champsRef.childByAppendingPath(champKey).childByAppendingPath("matches")
    .queryOrderedByValue().queryStartingAtValue(currentTimestamp)
    .queryLimitedToFirst(20)
    .observeEventType(.ChildAdded, withBlock: { (snapshot) in
        let key = snapshot.key
        matchesRef.childByAppendingPath(key).observeSingleEventOfType(.Value, withBlock: { (matchSnapshot) in
            // code
        })
    })

答案 1 :(得分:0)

在firebase中,您只能过滤queryOrderedBy(child: String)键。在我的情况下,我需要过滤多个日期范围(每个都是UITableView中的一个部分),并在这些排序中单独的字段。解决方案是使用FUISortedArray,它采用sortDescriptor (DataSnapshot, DataSnapshot) -> ComparisonResult

相关问题