我在 Viewcontroller
中使用了 JSQMessagesViewController
。聊天以匿名用户打开。聊天工作正常,但我需要对数据库进行一些更改。因为数据库是它的火力基地。当任何消息进入它显示的数据库时,我正在我的数据库中创建一个 child ,首先它显示名为“消息”的 child ,并在消息下显示所有聊天消息,我想删除这个 child ,直接聊天应该在它进入数据库时显示,并且还应该直接接收所有消息,而不会干扰数据库中的任何子项。我的聊天代码是这样的,
import UIKit
import Firebase
import FirebaseDatabase
@objc class ChatViewViewController: JSQMessagesViewController, UINavigationControllerDelegate{
var ref: DatabaseReference!
var Name : String?
private var messages = [JSQMessage]()
lazy var messageRef = Database.database().reference().child("Message")
var newMessageRefHandle: DatabaseHandle?
lazy var outgoingBubbleImageView: JSQMessagesBubbleImage = self.setupOutgoingBubble()
lazy var incomingBubbleImageView: JSQMessagesBubbleImage = self.setupIncomingBubble()
private var updatedMessageRefHandle: DatabaseHandle?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Chat Room"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))
self.ref = Database.database().reference(fromURL: "Database URL")
guard let str = UserDefaults.standard.string(forKey: "name") else {
return
}
senderDisplayName = str
self.senderId = Auth.auth().currentUser?.uid as NSString?! as String!
collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero
collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero
observeMessages()
// Do any additional setup after loading the view.
}
发送按钮代码是这个,
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let itemRef = messageRef.childByAutoId()
let messageItem = [
"senderId": senderId!,
"senderName": senderDisplayName!,
"text": text!,
]
itemRef.setValue(messageItem)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
collectionView.reloadData()
finishSendingMessage()
}
在 UI 中显示消息是这样的,
private func observeMessages() {
//messageRef = channelRef!.child("messages")
// 1.
let messageQuery = messageRef.queryLimited(toLast:25)
// 2. We can use the observe method to listen for new
// messages being written to the Firebase DB
newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) -> Void in
// 3
let messageData = snapshot.value as! Dictionary<String, String>
if let id = messageData["senderId"] as String!, let name = messageData["senderName"] as String!, let text = messageData["text"] as String!, text.characters.count > 0 {
// 4
self.addMessage(withId: id, name: name, text: text)
// 5
self.finishReceivingMessage()
}
})
updatedMessageRefHandle = messageRef.observe(.childChanged, with: { (snapshot) in
})
}
我不知道我是否完全理解您的问题,但据我所知,您正试图从数据库中删除 Message
层。您应该可以通过更改文件顶部的这一行来完成此操作
lazy var messageRef = Database.database().reference().child("Message")
to ->
lazy var messageRef = Database.database().reference()
这将删除该层。如果这不是您所描述的问题,请告诉我。
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |