2015-09-16 33 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