我将JSQMessageViewController用于我的实时聊天应用程序UI,并将firebase用于我的聊天应用程序数据库。对于文本消息和图像消息,加载仍然认为可以,但是对于音频消息,则需要很长时间。这是我获取音频消息的代码:
func observeMessages() {
let userMessagesRef = Database.database().reference().child("messages").child(Id).child(senderId).queryLimited(toLast: 50)
userMessagesRef.observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
let messagesRef = Database.database().reference().child("messages").child(messageId)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
if (dictionary["fromId"] as? String ?? "" == self.userId ? dictionary["toId"] as? String ?? "" : dictionary["fromId"] as? String ?? "") == self.contactLists.first?.id{
let date = NSDate(timeIntervalSince1970: dictionary["timestamp"] as? Double ?? 0.0)
let textString = dictionary["text"] as? String ?? ""
let imgString = dictionary["imageUrl"] as? String ?? ""
let voiceString = dictionary["voiceUrl"] as? String ?? ""
if textString == "image"{
let imageView = AsyncPhotoMediaItem(withURL: URL(string: imgString)!)
let message = JSQMessage(senderId: dictionary["toId"] as? String ?? "", senderDisplayName: "", date: date as Date, media: imageView)
self.messages.append(message!)
}else if textString == "voice"{
print("voice msg")
let url = URL(string: voiceString)
let data = try? Data(contentsOf: url!)
let voiceData = data
let voice1 = JSQAudioMediaItem(data: voiceData)
let message = JSQMessage(senderId: dictionary["toId"] as? String ?? "", senderDisplayName: "", date: date as Date, media: voice1)
self.messages.append(message!)
}else{
print("text msg")
let message = JSQMessage(senderId: dictionary["toId"] as? String ?? "", senderDisplayName: "", date: date as Date, text: dictionary["text"] as? String ?? "")
self.messages.append(message!)
}
}; DispatchQueue.main.async {
self.collectionView?.reloadData()
}
self.finishReceivingMessage(animated: true)
}, withCancel: nil)
}, withCancel: nil)
}
有人可以帮助我吗?还是有其他方法可以做到或增强它?请帮助我