2015-09-16 32 views
1

我正在使用Firebase iOS SDK构建一个聊天系统,该聊天系统可让我的用户连接到一些随机聊天的“聊天室”。在房间内,我想向他们显示当前连接的人员总数。问题是我不知道该怎么做。连接的用户数量应在特定用户的连接和断开连接时更新。我不知道该从哪里开始,该怎么做。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 
    } 
}) 

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; 
    } 
}]; 
+0

:)谢谢,但你能否请我提供一个客观的例子,遵循? – user1341993

+0

如果你在你的问题中提到这些要求,而不是在有人为你写了答案之后,这将会非常有帮助。 –

+0

对不起,我下次要去做。 – user1341993