Firebase iOS SDK - 连接用户数

Firebase iOS SDK - Count connected users

我正在使用 Firebase iOS SDK 构建一个聊天系统,让我的用户可以连接到一些随机的 "rooms" 他们可以一起聊天的地方。在房间内,我想向他们显示当前连接的总人数。问题是我不知道该怎么做。连接的用户数量应在特定用户的连接和断开连接时更新。我不知道从哪里开始和做什么。

这很简单:)

每当一个用户 authenticates/joins 一个房间将他们保存到活跃用户列表中。

Swift

let ref = Firebase(url: "<your-firebase-db>")
ref.observeAuthEventWithBlock { authData in
  if authData != nil {
    // 1 - Get the ref
    let activeUsersRef = Firebase(url: '<your-firebase-db>/activeUsers')
    // 2 - Create a unique ref
    let singleUserRef = activeUsersRef.childByAutoId()
    // 3 - Add them to the list of online users
    singleUserRef.setValue(authData.providerData["email"])
    // 4 - When they drop their connection, remove them
    singleUserRef.onDisconnectRemoveValue()
  }
}

Objective-C

Firebase *ref = [[Firebase alloc] initWithUrl: @"<your-firebase-db>"];
[ref observeAuthEventWithBlock: ^(FAuthData *authData) {
  Firebase *activeUsersRef = [[Firebase alloc] initWithUrl: @"<your-firebase-db>/activeUsers"];
  Firebase *singleUserRef = [activeUsersRef childByAutoId];
  [singleUserRef setValue: @"Whatever-the-key-is"];
  [singleUserRef onDisconnectRemoveValue];
}];

上面的代码片段将维护一个活跃用户列表。

您现在需要做的就是显示计数。

Swift

// Listen to the same ref as above
let activeUsersRef = Firebase(url: 'firebase-db.firebaseio.com/activeUsers')
activeUsersRef.observeEventType(.Value, withBlock: { (snapshot: FDataSnapshot!) in
  var count = 0
  // if the snapshot exists, get the children
  if snapshot.exists() {
    count = snapshot.childrenCount
  }
})

Objective-C

Firebase *activeUsersRef = [[Firebase alloc] initWithUrl: @"<your-firebase-db>/activeUsers"];
[activeUsersRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
  NSUInteger count = 0;
  if ([snapshot exists]) {
    count = snapshot.childrenCount;
  }
}];