4

I've seen similar questions but the answers haven't worked for me. Code isn't pretty but here goes. I've implemented MessageKit and my images are not showing up when previous messages are loaded or when an image is sent. The images are showing as empty chat bubbles as shown in the image.enter image description here

  1. Empty images - I've printed the URLs so I know the values are coming from the database. I have a function called loadMessages that pulls the data from MySQL. Somehow it's not passing the image information to messageKit although the texts are coming through fine. Here is the code:

Message.swift file

    private struct ImageMediaItem: MediaItem {

    var url: URL?
    var image: UIImage?
    var placeholderImage: UIImage
    var size: CGSize

    init(image: UIImage) {
        self.image = image
        self.size = CGSize(width: 240, height: 240)
        self.placeholderImage = UIImage()
    }

}

    internal struct Message: MessageType {
    var messageId: String
    var sender: SenderType {
        return user
    }
    var sentDate: Date
    var kind: MessageKind

    var user: User

    private init(kind: MessageKind, user: User, messageId: String, date: Date) {
        self.kind = kind
        self.user = user
        self.messageId = messageId
        self.sentDate = date
    }

    init(custom: Any?, user: User, messageId: String, date: Date) {
        self.init(kind: .custom(custom), user: user, messageId: messageId, date: date)
    }

    init(text: String, user: User, messageId: String, date: Date) {
        self.init(kind: .text(text), user: user, messageId: messageId, date: date)
    }

    init(attributedText: NSAttributedString, user: User, messageId: String, date: Date) {
        self.init(kind: .attributedText(attributedText), user: user, messageId: messageId, date: date)
    }

    init(image: UIImage, user: User, messageId: String, date: Date) {
        let mediaItem = ImageMediaItem(image: image)
        self.init(kind: .photo(mediaItem), user: user, messageId: messageId, date: date)
    }

    init(thumbnail: UIImage, user: User, messageId: String, date: Date) {
        let mediaItem = ImageMediaItem(image: thumbnail)
        self.init(kind: .video(mediaItem), user: user, messageId: messageId, date: date)
    }

}

loadMessages function in the DirectMessage.swift file

func loadMessages(offset: Int, limit: Int) {


       let url = URL(string: "https://localhost/message.php")
       let body = "username=\(me)&uuid=\(uuid)&recipient_id=\(meid)&limit=\(limit)&offset=\(offset)"
       var request = URLRequest(url: url!)
       request.httpMethod = "POST"
       request.httpBody = body.data(using: String.Encoding.utf8)

       URLSession.shared.dataTask(with: request) { (data, response, error) in
           DispatchQueue.main.async {

               if error != nil {
                   Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
                   return
               }

               do {
                   guard let data = data else {
                       Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
                       self.isLoading = false
                       return
                   }
                   let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary

                                          guard let parseJSON = json else {
                                              print("Error while parsing")
                                              return
                                          }
                   guard let posts = parseJSON["messages"] as? [NSDictionary] else {
                                              self.isLoading = false
                       print("Error while parseJSONing")
                                              return
                                          }

                   self.hhmessages = posts as [AnyObject?] as [AnyObject]

                   for i in 0 ..< self.hhmessages.count {
                       let meid = self.hhmessages[i]["sender_id"]! as! String
                       let sender = User(senderId: self.hhmessages[i]["sender_id"]! as! String, displayName: (self.hhmessages[i]["sender"])! as! String)

                       AppSettings.senderId = self.hhmessages[i]["sender_id"] as? String
                       AppSettings.displayName = self.hhmessages[i]["sender"] as? String

                       let member = self.hhmessages[i]["recipient"]
                       let text = self.hhmessages[i]["messagetext"] as? String
                       let uuid = self.hhmessages[i]["uuid"] as! String
                       let sid = self.hhmessages[i]["sender_id"]
                       let message_id = self.hhmessages[i]["notesid"] as? String
                       let path = self.hhmessages[i]["uploadpath"] as! String

                    let sentDate = self.hhmessages[i]["date"] as! String
                       let dateFormatter = DateFormatter()
                       dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                       dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
                       if let date = dateFormatter.date(from: sentDate) {
                       }

                       if path.isEmpty {
                        let message = Message(text: text!, user: sender, messageId: uuid, date: self.date)
                           self.messages.append(message)

                       }
                       else {

                        let pictureURL = URL(string: path)!
                        print(pictureURL)
                           URLSession(configuration: .default).dataTask(with: pictureURL) { (data, response, error) in
                               if let image = UIImage(data: data!) {

                                   DispatchQueue.main.async {
                                    let message = Message(image: image, user: sender, messageId: uuid, date: self.date)                                  
                                       self.messages.append(message)

                                   }
                               }
                           }


                       }
                       self.messageList = self.messages
                       self.messagesCollectionView.reloadData()
                    DispatchQueue.main.async {
                        self.messagesCollectionView.scrollToItem(at: IndexPath(row: 0, section: self.messages.count - 1), at: .top, animated: false)
                       }

                   }
                   return


               } catch {
                   Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
                   self.isLoading = false

                   return
               }

           }
           }.resume()

   }

MessagesDisplayDelegate

    func configureMediaMessageImageView(_ imageView: UIImageView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {

}

extension UIImageView {
 func load(url: URL) {
   DispatchQueue.global().async { [weak self] in
       if let data = try? Data(contentsOf: url) {
           if let image = UIImage(data: data) {
               DispatchQueue.main.async {
                   self?.image = image
               }
           }
       }
    }
  }
}
techgirl
  • 293
  • 1
  • 3
  • 18
  • 1
    Are you sure the key for image is `uploadpath`? Usually this indicates that there're two different urls one for uploading image from the client, and one for downloading image from the server. Could it be that the JSON also contains `downloadpath`? – inokey Mar 12 '20 at 06:14
  • @inokey I’ve confirmed that uploadpath is what’s being used in the api – techgirl Mar 12 '20 at 15:36

0 Answers0