【发布时间】:2017-01-26 12:50:03
【问题描述】:
我正在构建一个聊天应用程序并使用以下数据结构:
基本上在user_chats 中,我会跟踪用户正在进行的所有对话,以及该对话中的last_message 是什么,以便稍后我可以在表格视图中显示它。
在 messages 节点中,我通过自动 ID 存储给定对话的所有消息。
现在,当用户发送消息时,它应该出现在给定对话的 messages 节点中,以及两个用户的对话的 last_message 中。
在我使用调度组并单独调用 Firebase 之前,但这似乎非常不可靠且效率低下。
如何有效地同时更新所有值?
补充:这种结构适合一对一聊天应用吗?
使用工作代码更新:
我已经设法使用扇出方法更新了所有值。
这是我的代码:
NSDictionary *lastMessageDict = @{[self chatToUserID:userID] : @{@"last_message" : messageBody}};
NSDictionary *singleMessageDict = @{@"body" : messageBody, @"time_stamp" : kTimeStamp, @"sender" : uID};
NSString *autoID = [[self.databaseReference child:[NSString stringWithFormat:@"messages/%@/messages",[self chatToUserID:userID]]] childByAutoId].key;
NSDictionary *messagesDict = @{[self chatToUserID:userID] : @{@"init" : facebookUserID , @"messages" : @{autoID : singleMessageDict}}};
//Create fan out object
NSMutableDictionary *fanOut = [NSMutableDictionary new];
[fanOut addEntriesFromDictionary:@{[NSString stringWithFormat:@"user_chats/%@",uID] : lastMessageDict}];
[fanOut addEntriesFromDictionary:@{[NSString stringWithFormat:@"user_chats/%@",userID] : lastMessageDict}];
[fanOut addEntriesFromDictionary:@{@"messages" : messagesDict}];
[self.databaseReference updateChildValues:fanOut withCompletionBlock:^(NSError *error,FIRDatabaseReference *reference){
if(error){
NSLog(@"Error: %@",error);
}
else{
NSLog(@"updated!");
}
}];
【问题讨论】:
-
您在问题中包含了 JSON 树的图片。请将其替换为实际的 JSON 作为文本,您可以通过单击 your Firebase Database console 中的导出 JSON 链接轻松获得。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,总的来说这只是一件好事。
-
除此之外:是的,您可以使用单个多位置更新一次性发送更新。请参阅此博客文章:firebase.googleblog.com/2015/10/…。如果您无法使其正常工作,请发布您拥有的代码。
-
@FrankvanPuffelen 非常感谢!我让它工作了,我唯一不知道的是如何给每条消息一个唯一的 ID。你能帮我解决这个问题吗?我更新了我的代码!
-
只需使用
let uniqueId = self.databaseReference.childByAutoId().key生成具有唯一 ID 的 ref,然后在字典中的路径中使用该键。 -
谢谢!更新了我的代码供其他人查看。请将此作为答案发布,以便我给您积分!
标签: ios firebase firebase-realtime-database