我正在努力在 Firebase 100% 上创建一个 Tinder 克隆,从身份验证到实时聊天。我已经成功地在 Messages View Controller 的 tableview 上向用户展示了他们相互感兴趣的匹配。现在我的问题在于为匹配的用户创建一个聊天室。解决这个问题的最有效方法是什么?
我是否从 Firebase 基本参考创建聊天室对象,并将聊天室分配给两个用户,并将聊天室的密钥插入两个用户?
我只是对如何去做感到困惑,因为我已经编写了从上面那个想法开始的代码,但是我如何确保一旦创建了聊天室,用户将永远拥有那个房间,而不是为他们初始化了一个全新的房间?我想我的做法是错误的......我现在拥有代码的方式,当我运行这段代码时,聊天室将在消息视图控制器上创建:
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()
})
}