我用过这个模型:
import Foundation
class Chat {
var message: String?
var senderID: String
var receiverID: String
var timestamp : String
init(messageTextString: String?, senderIDNumber: String, receiverIDNumber: String, timeStampString: String){
message = messageTextString
senderID = senderIDNumber
receiverID = receiverIDNumber
timestamp = timeStampString
}
}
对于ChatViewController:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return chats.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ChatCollectionViewCell
let senderIDNumber = Auth.auth().currentUser?.uid
if chats[indexPath.row].senderID == senderIDNumber {
if let chatsText = chats[indexPath.row].message{
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
cell.messageSend.frame = CGRect(x:8,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
cell.textBubbleView.frame = CGRect(x:0,y:0,width:estimatedFrame.width + 16 + 8, height:estimatedFrame.height + 20)
//showOutgoingMessage(text: chats[indexPath.row].message)
}
cell.messageSend.text = chats[indexPath.row].message
}
else {
/*cell.messageReceived.text = chats[indexPath.row].message */
let chatsText = chats[indexPath.row].message
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText!).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
cell.messageSend.frame = CGRect(x:view.frame.width - estimatedFrame.width,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
cell.textBubbleView.frame = CGRect(x:view.frame.width - estimatedFrame.width,y:0,width:estimatedFrame.width + 16 + 8, height:estimatedFrame.height + 20)
}
return cell
}
@objc func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if let chatsText = chats[indexPath.row].message {
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
return CGSize(width: view.frame.width, height: estimatedFrame.height + 20)
}
return CGSize(width: view.frame.width, height: 200)
}
func loadPosts() {
let ref = Database.database().reference()
let senderIDNumber = Auth.auth().currentUser?.uid
ref.child("chats").queryOrdered(byChild: "senderID").queryEqual(toValue: senderIDNumber).observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
let messageText = dict["message"] as! String
let senderIDNumber = dict["senderID"] as! String
let receiverIDNumber = dict["receiverID"] as? String
let timestamp = dict["timestamp"] as? String
let chat = Chat(messageTextString: messageText, senderIDNumber: senderIDNumber, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!)
//append(post) to array
self.chats.append(chat)
print(self.chats)
self.collectionView.reloadData()
}
}
}
func loadPostsReceivedMessage() {
let ref = Database.database().reference()
ref.child("chats").queryOrdered(byChild: "receiverID").queryEqual(toValue: receiverIDNumber).observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
let messageText = dict["message"] as! String
let senderIDNumber = dict["senderID"] as! String
let receiverIDNumber = dict["receiverID"] as? String
let timestamp = dict["timestamp"] as? String
let chat = Chat(messageTextString: messageText, senderIDNumber: senderIDNumber, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!)
self.chats.append(chat)
print(self.chats)
self.collectionView.reloadData()
}
}
}
}
我希望能够区分Outgoing和Incoming消息,但无法区分。我确实想过创建一个inComing布尔值来区分传出和传入消息;但不知道如何实施。 我需要帮助和建议,很多
答案 0 :(得分:0)
Firebase无法进行查询!!!(特别是多重排序)..需要迁移到firestorm(firebase存储的新Beta版本)或使用angular。
答案 1 :(得分:0)
能够区分已发送的消息和收到的消息就像向Chat对象添加属性一样简单,因此您可能会遇到以下情况:
class Chat {
var message: String
var senderID: String
var receiverID: String
var timestamp : String
var isFromCurrentUser: Bool = false // You'll only need to change this property if the message is from the current sender.
init(messageTextString: String?, senderIDNumber: String, receiverIDNumber: String, timeStampString: String){
self.message = messageTextString
self.senderID = senderIDNumber
self.receiverID = receiverIDNumber
self.timestamp = timeStampString
}
}
修改对象后,您需要查看获取数据的方式。我建议将loadPosts()
重命名为listenForChatItemAdded()
并将功能更改为以下内容:
注意:使用查询并不是必需的。当您只查看某组数据时,查询特别有用;在这里,您最好抓取数据,并在初始化对象后对其进行排序。
func loadPosts() {
let ref = Database.database().reference()
let senderIDNumber = Auth.auth().currentUser?.uid
ref.child("chats").observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
let messageText = dict["message"] as! String
let senderIDNumber = dict["senderID"] as! String
let receiverIDNumber = dict["receiverID"] as? String
let timestamp = dict["timestamp"] as? String
let chat = Chat(messageTextString: messageText, senderIDNumber: senderIDNumber, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!)
let currentUserUID = Auth().auth().currentUser!.uid
if senderID == currentUserUID {
chat.isFromCurrentUser = true
}
//append(post) to array
self.chats.append(chat)
//after adding the new chat tot the array, sort the array
let sorted = filtered.sorted { (chat1, chat2) -> Bool in
return chat1.timestamp > chat2.timestamp
}
// update the current array with the sorted array
self.chats = sorted
// reload the collectionView
self.collectionView.reloadData()
}
}
}
最后,只需检查我们创建的属性,以确定如何在视觉上设置单元格。我将创建两个UICollectionViewCell的子类。一个用于发送者,一个用于接收者。如果聊天是由当前用户发送的,则使用发送方子类创建一个单元格,如果聊天是由其他任何人发送的,则使用接收方子类。
希望这有帮助, 干杯!