我使用Firebase iOS SDK构建了一个聊天系统,让我的用户可以连接到一些随机的"房间"他们可以在一起聊天的地方在房间内,我想向他们显示当前连接的总人数。问题是我不知道该怎么做。应在特定用户的连接和断开连接上更新连接的用户数。我不知道从哪里开始和做什么。
答案 0 :(得分:5)
这很简单:)
每当用户验证/加入会议室时,请将其保存到活动用户列表中。
<强>夫特强>
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()
}
}
<强>目标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];
}];
上面的代码段会维护一个活跃用户列表。
您现在需要做的只是显示计数。
<强>夫特强>
// 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
}
})
<强>目标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;
}
}];