iosswiftfirebase-realtime-databasefirebase-storagejsqmessagesviewcontroller

JSQMessage with media after text message's


I'm trying to load messages with JSQMessagesViewController. But mediaMessages are added to the array last, although they should not be. Images should be between text messages, but they appear last. I think I need to add an empty bubble for images or something like that.

JSQMessage with media This mediaMessage must be between 2 and 3 message

My code:

let query = Database.database().reference().child("chats").child(chatId!).queryLimited(toLast: 10)
    _ = query.observe(.childAdded, with: { (snapshot) in
        if  let data        = snapshot.value as? [String: AnyObject],
            let id          = data["userId"],
            let name        = self.chatName,
            let text        = data["content"]
        {
            if let image = data["image"] {
                let storageKey = "images/" + self.chatId! + "/" + (image as! String)
                let storageRef = Storage.storage().reference(withPath: storageKey)
                storageRef.getData(maxSize: 1 * 1000 * 1000, completion: { (imageData, err) in
                    if err != nil {
                        print("Error with storage")
                        return
                    }
                    let imageMessage = UIImage(data: imageData!)
                    let mediaItem = JSQPhotoMediaItem(image: imageMessage)
                    if let message = JSQMessage(senderId: id as! String, displayName: name, media: mediaItem) {
                        self.messages.append(message)
                        self.finishReceivingMessage()

                    }
                })

            } else {
                if let message = JSQMessage(senderId: id as! String, displayName: name, text: text as! String)
                {
                    self.messages.append(message)
                    self.finishReceivingMessage()
                }
            }
        }
    })

Solution

  • I changed the logic of loading messages. https://www.raywenderlich.com/140836/firebase-tutorial-real-time-chat-2