ios - Swift - 如何在 Firebase 中创建(全部)关注用户?

标签 ios swift firebase firebase-realtime-database

我想使用 .indexOn: timestamp 从关注的用户那里获取最新的帖子(我正在使用 UTC 时间来做到这一点)但我不知道如何同时过滤按时间戳排序的关注帖子以便能够使用limitToLast 在这种情况下正确吗?

posts
   post_id_0
      timestamp: _
      ownerID: user_id_0
   ...


users
   user_id_0
      following
         user_id_0: true
         user_id_1: true
      followers
         user_id_x: true
         user_id_y: true
   ...

最佳答案

如果您想按时间戳排序并将其限制为最后一个(这将是最近的)

    let postsRef = self.myRootRef.childByAppendingPath("posts")

    postsRef.queryOrderedByChild("timestamp").queryLimitedToLast(1)
       .observeSingleEventOfType(.Value, withBlock: { snapshot in
        if ( snapshot.value is NSNull ) {
            print("not found")

        } else {
            for child in snapshot.children {

                let q = child.value["ownerID"] as! String
                print(q)
            }

        }
    })

如果我理解这个问题,您还想将帖子限制为特定用户。换句话说,您想获取 user_0 创建的最新帖子。 (即查询:where xx && yy)

有几种方法可以做到这一点

1) 跟踪那些在用户节点内的帖子

users
  user_id_0
     following
       xxxx
     followers
       yyyy
     3_most_recent_posts
       post_id_3: true
       post_id_2: true
       post_id_1: true

然后您可以直接获取特定的帖子。

2) 第二种选择是格式化您的 Firebase 以匹配您想要获得的内容:

posts
   post_id_0
       owner_timestamp: user_id_0_20160611081433

然后,查询 posts 节点以获取从 user_id_0_ 开始并将其限制为最后一个 x 的值

    postsRef.queryOrderedByChild("owner_timestamp")
       .queryStartingAtValue("user_id_0_")
       .queryLimitedToLast(1)
       .observeSingleEventOfType(.Value, withBlock: { snapshot in
        if ( snapshot.value is NSNull ) {
            print("not found")

        } else {
            for child in snapshot.children {

                let q = child.value["ownerID"] as! String
                print(q)
            }

        }
    })

关于ios - Swift - 如何在 Firebase 中创建(全部)关注用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37753536/

相关文章:

ios - SwiftUI - iOS - 当应用程序进入后台并返回事件状态时,使用 scenePhase 会导致 View 弹出

ios - 使用 NSLayoutAnchor.constraintEqualToSystemSpacingAfter 时出现控制台警告

ios - 从 NIB 加载 View 返回零帧 View - 怎么办?

ios - SKTransition crossFadeWithDuration 在 Swift 中无法正常工作

javascript - Cloud Functions for Firebase 上的 Passport.js 给出错误 "Cannot read property ' apply' of undefined"

iphone - 调用 UITableView 的 reloadData 方法时需要使用@synchronized 吗?

ios - 字符串下标耗时长

swift - 我怎么知道完成 block 没有执行但方法完成了?

javascript - Firebase 电话身份验证 : Is it possible to only check if the telephone exists in Authentication and not Sign Up the user automatically?

objective-c - 如何从 firebase 数据库读取一小节