Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift Can';切换到另一个聊天室时,不要从聊天室视图控制器中删除消息_Swift_Firebase Realtime Database_Uicollectionview_Chat_Jsqmessagesviewcontroller - Fatal编程技术网

Swift Can';切换到另一个聊天室时,不要从聊天室视图控制器中删除消息

Swift Can';切换到另一个聊天室时,不要从聊天室视图控制器中删除消息,swift,firebase-realtime-database,uicollectionview,chat,jsqmessagesviewcontroller,Swift,Firebase Realtime Database,Uicollectionview,Chat,Jsqmessagesviewcontroller,下面是我的ViewDidDisplay功能,它仅在用户第一次打开聊天室时成功加载所有以前的消息。之后,当用户退出一个聊天室,然后开始另一个聊天室时,来自上一个聊天室的消息将被添加到这些消息的末尾,这些消息位于顶部,而那些特定于最近的聊天室的消息将被添加到这些消息的末尾。显然不理想。我试图在单击chatVC的后退按钮退出时删除messages数组中的所有消息(如下所示),但这会导致应用程序在尝试加载新聊天时崩溃。具体地说,它在覆盖func collectionView(qlectionview:j

下面是我的ViewDidDisplay功能,它仅在用户第一次打开聊天室时成功加载所有以前的消息。之后,当用户退出一个聊天室,然后开始另一个聊天室时,来自上一个聊天室的消息将被添加到这些消息的末尾,这些消息位于顶部,而那些特定于最近的聊天室的消息将被添加到这些消息的末尾。显然不理想。我试图在单击chatVC的后退按钮退出时删除messages数组中的所有消息(如下所示),但这会导致应用程序在尝试加载新聊天时崩溃。具体地说,它在覆盖func collectionView(qlectionview:jsqMessageCollectionView!,messageDataForItemAt indexPath:indexPath!)->JSQMessageData上崩溃!{ 返回消息[indexPath.item] }(另见下文)


此外,在“self.messages.removeAll()”之后添加“self.collectionView.reloadData()”会导致转到其他聊天室时错误地以空白开头。比撞车好一点,但不多。如何清除消息,以便更改用户消息的用户,使聊天视图控制器只加载该用户的消息,而不加载以前加载的消息或根本不加载消息?

这是因为您已将所有逻辑都放在
视图显示中
此方法不会像您在此处假设的那样频繁调用。因此,当您在其他地方导航时,视图不会被破坏,因此当您返回视图时,它会更快。您应该将此逻辑移到另一个函数中。仅将设置视图的内容放入
视图显示
,即设置背景色。您可能希望此逻辑出现在
viewDidLoad()
中,这将分配更多您正在寻找的行为

override func viewDidAppear(_ animated: Bool) {
    if presentedChatVCFromChatListVC{
        chatRef.child(chatListingID).child("messages").observe(.value, with: { snapshot in
            print("snapshot.value is \(snapshot.value)")
            for child in snapshot.children {
                let childData = child as! FIRDataSnapshot
                print("childData is \(childData)")
                if let dict = childData.value as? NSDictionary{
                    let mediaType = dict["MediaType"] as! String
                    let senderId = dict["senderId"] as! String
                    let senderName = dict["senderName"] as! String

                    self.observeUsers(senderId)
                    switch mediaType {

                    case "TEXT":

                        let text = dict["text"] as! String
                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
                        self.collectionView.reloadData()

                    case "PHOTO":

                        let photo = JSQPhotoMediaItem(image: nil)
                        let fileUrl = dict["fileUrl"] as! String
                        let downloader = SDWebImageDownloader.shared()
                        downloader.downloadImage(with: URL(string: fileUrl)!, options: [], progress: nil, completed: { (image, data, error, finished) in
                            DispatchQueue.main.async(execute: {
                                photo?.image = image
                                self.collectionView.reloadData()
                            })
                        })

                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
                        if self.senderId == senderId {
                            photo?.appliesMediaViewMaskAsOutgoing = true
                        }else{
                            photo?.appliesMediaViewMaskAsOutgoing = false
                        }

                    case "VIDEO":

                        let fileUrl = dict["fileUrl"] as! String
                        let video = URL(string: fileUrl)!
                        let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: videoItem))

                        if self.senderId == senderId {
                            videoItem?.appliesMediaViewMaskAsOutgoing = true
                        } else {
                            videoItem?.appliesMediaViewMaskAsOutgoing = false
                        }

                    default:
                        print("unknown data type")

                    }
                }
                self.collectionView.reloadData()
            }
        })
    }else{
        chatRef.queryOrdered(byChild: "otherUserID").queryEqual(toValue: otherUID).observe(.value, with:{
                snapshot in
            print("snapshot.value is \(snapshot.value)")
            for child in snapshot.children {
                let childData = child as! FIRDataSnapshot
                print("childData is \(childData)")
                if let dict = childData.value as? NSDictionary{
                    let temp = dict["userID"] as! String
                    if temp == userID{
                        chatListingID = dict["chatRoomKey"] as! String
                        self.chatRef.child(chatListingID).child("messages").observe(.value, with:{
                            snapshot in
                            for child1 in snapshot.children {
                                let childData1 = child1 as! FIRDataSnapshot
                                print("childData1 is \(childData1)")
                                if let dict1 = childData1.value as? NSDictionary{
                                    let mediaType = dict1["MediaType"] as! String
                                    let senderId = dict1["senderId"] as! String
                                    let senderName = dict1["senderName"] as! String

                                    self.observeUsers(senderId)
                                    switch mediaType {

                                    case "TEXT":

                                        let text = dict1["text"] as! String
                                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
                                        self.collectionView.reloadData()

                                    case "PHOTO":

                                        let photo = JSQPhotoMediaItem(image: nil)
                                        let fileUrl = dict1["fileUrl"] as! String
                                        let downloader = SDWebImageDownloader.shared()
                                        downloader.downloadImage(with: URL(string: fileUrl)!, options: [], progress: nil, completed: { (image, data, error, finished) in
                                            DispatchQueue.main.async(execute: {
                                                photo?.image = image
                                                self.collectionView.reloadData()
                                            })
                                        })

                                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
                                        if self.senderId == senderId {
                                            photo?.appliesMediaViewMaskAsOutgoing = true
                                        }else{
                                            photo?.appliesMediaViewMaskAsOutgoing = false
                                        }

                                    case "VIDEO":

                                        let fileUrl = dict1["fileUrl"] as! String
                                        let video = URL(string: fileUrl)!
                                        let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
                                        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: videoItem))

                                        if self.senderId == senderId {
                                            videoItem?.appliesMediaViewMaskAsOutgoing = true
                                        } else {
                                            videoItem?.appliesMediaViewMaskAsOutgoing = false
                                        }

                                    default:
                                        print("unknown data type")
                                    }
                                }
                            }
                        })
                    }
                }
            self.collectionView.reloadData()
            }
        })
    }
    observeTyping()
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
    return messages[indexPath.item]
}
func backButtonDidClick(){
    self.messages.removeAll()
    dismiss(animated: true, completion: nil)
}