MessageKit-如何在MessagesViewController的子类中异步加载图像?

时间:2019-01-03 07:17:42

标签: ios swift messagekit

最近,我一直在开发聊天应用程序,并在通过聊天异步加载图像时遇到麻烦。

使用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初始化图像kind = .photo(Image(url: url))

这似乎不起作用。

1 个答案:

答案 0 :(得分:1)

此后,我了解到MessageKit在MessagesDisplayDelegate中提供了一个称为

的委托方法。
func configureMediaMessageImageView(_ imageView: UIImageView,
                                    for message: MessageType,
                                    at indexPath: IndexPath,
                                    in messagesCollectionView: MessagesCollectionView)

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

我正在使用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)
}