最近我一直在开发一个聊天应用程序,但在用聊天异步加载图像时遇到了问题。

使用 MessageKit - 2.0

我试过这个

import MessageKit

class Image: MediaItem {
  var url: URL?

  var image: UIImage?

  var placeholderImage: UIImage

  var size: CGSize

  init(url: URL) {
    self.url = url
    self.size = CGSize(width: 240, height: 240)
    self.placeholderImage = UIImage()
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url) {
            if let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    self.image = image
                }
            }
        }
    }
}

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

}

然后我用 MessageType 初始化 Image kind = .photo(Image(url: url))
这似乎不起作用。

最佳答案

从那以后,我了解到 MessageKit 在 MessagesDisplayDelegate 中提供了一个名为的委托(delegate)方法

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

我们可以使用此委托(delegate)方法异步加载给定消息的图像。

我正在使用 UIImageView 扩展来帮助解决这个问题
import UIKit

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
                }
            }
        }
     }
   }
 }

所以的解决方案如下
func configureMediaMessageImageView(_ imageView: UIImageView,
                                    for message: MessageType,
                                    at indexPath: IndexPath,
                                    in messagesCollectionView: MessagesCollectionView) {
    /*acquire url for the image in my case i had a
    custom type Message which stored  the image url */
    guard
        let msg = message as? Message,
        let url = msg.downloadURL
    else { return }
    imageView.load(url: url)
}

关于ios - MessageKit - 如何在 MessagesViewController 的子类中异步加载图像?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54017910/

10-10 04:38