对于两个匹配的用户,在Firebase / Swift上创build聊天室的首选方式是什么?

我正在致力于在Firebase 100%上创build一个Tinder克隆,从身份validation到实时聊天。 我已经成功地向消息视图控制器的tableview显示用户他们相互感兴趣的匹配。 现在我的问题在于为匹配的用户创build一个聊天室。 什么是最有效的方式去做这个?

是否从Firebase基础参考创build聊天室对象,然后将聊天室分配给两个用户,并将聊天室的密钥插入两个用户?

我只是混淆了如何去做,因为我已经写了代码开始上面这个想法,但我怎样才能确保一旦聊天室创build,用户将永远有这个房间,而不是一个全新的房间为他们初始化? 我想我错了…现在我有了代码的方式,聊天室将在消息视图控制器上运行时,我运行这段代码:

override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) currentUserKey = DataService.ds.REF_CURRENT_USER.key DataService.ds.REF_CURRENT_USER.observeSingleEventOfType(.Value, withBlock: { snapshot in if let matchesInterestedIn = snapshot.value["matchesInterestedIn"] { if matchesInterestedIn != nil { for (_, value) in matchesInterestedIn as! [String: String] { self.currentUserInterests.append(value) } } } }) DataService.ds.REF_USERS.observeSingleEventOfType(.Value, withBlock: { snapshot in self.admirers = [Match]() self.matches = [Match]() if snapshot != nil { for potentialMatch in snapshot.children { let potentialMatchData = potentialMatch.valueInExportFormat() if potentialMatchData["matchesInterestedIn"] != nil { if let potentialMatchInterests = potentialMatchData["matchesInterestedIn"] as? Dictionary<String, String> { if potentialMatchInterests.values.contains(self.currentUserKey) { let interestedMatch = Match(snapshot: potentialMatch as! FDataSnapshot) self.admirers.append(interestedMatch) } } } } } if self.admirers.count > 0 { for potentialMatch in self.admirers { if self.currentUserInterests.contains(potentialMatch.key) { self.matches.append(potentialMatch) let chatRoomInitializer = ["user1": self.currentUserKey, "user2": potentialMatch.key] let chatRoomRef = DataService.ds.REF_CHATROOMS.childByAutoId() let chatRoomID = chatRoomRef.key // For some odd reason, the next two lines of code create an endless amount of chatroom objects from the base reference let currentUserChatRoomRef = DataService.ds.REF_CURRENT_USER.childByAppendingPath("chatrooms").childByAutoId() currentUserChatRoomRef.setValue(chatRoomID) let potentialMatchRef = DataService.ds.REF_USERS.childByAppendingPath(potentialMatch.key).childByAppendingPath("chatrooms").childByAutoId() potentialMatchRef.setValue(chatRoomRef.key) chatRoomRef.setValue(chatRoomInitializer) } } } self.tableView.reloadData() }) } 

通常的方法是根据该房间的用户创build房间名称。

所以如果你的uid是ron而我的puf是最后一个房间puf_ron

请注意,我在连接之前命令了uid,以便它们以相同的顺序排列,而不pipe是谁在用户列表中排在第一位。

这种方法不需要跟踪用户在哪个房间,并确保相同的两个(或更多)用户总是在同一个房间中结束。