我正在尝试在 Message Kit 的消息气泡中显示图像。据我所知,Message Kit 有很多类型的气泡。对于我的方法.photo(ImageMediaItem)
,我认为是最好的消息类型。我想在新创建的消息集合视图中看到加载的图像,或者这是个坏主意?我不确定如何解决这个任务,所以这是我自己的想法。我在这里找到的图像加载教程。为此,我创建了用于存储图像的结构:
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()
}
}
由于我从远程服务器接收到消息数据,我决定循环接收到的消息数据并在图像在数据中时向远程发送请求。这是处理服务器响应:
chatMd.chat?.unread?.forEach({ (message) in
var mKind:MessageKind = .text(message.body!)
DispatchQueue.main.async {
if message.body!.extractURLs().count > 0{
let link = message.body!.extractURLs()[0]
if link.absoluteString.contains("jpg") || link.absoluteString.contains("png") || link.absoluteString.contains("jpeg"){
mKind = .photo(ImageMediaItem(image: imageFromServerURL(urlString: link)))
}else{
mKind = .linkPreview(MockLinkItem(text: "nil", attributedText: nil, url: URL.init(string: link.absoluteString)!, title: link.lastPathComponent, teaser: "", thumbnailImage: #imageLiteral(resourceName: "attachment")))
}
}
}
})
}
对于链接获取,我使用了这样的扩展,也许它会很有用:
extension String {
func extractURLs() -> [URL] {
var urls : [URL] = []
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
detector.enumerateMatches(in: self, options: [], range: NSMakeRange(0, self.count), using: { (result, _, _) in
if let match = result, let url = match.url {
urls.append(url)
}
})
} catch let error as NSError {
print(error.localizedDescription)
}
return urls
}
}
因此,正如您所见,图像获取从这里开始:
mKind = .photo(ImageMediaItem(image: imageFromServerURL(urlString: link)))
对于图像获取,我创建了函数:
func imageFromServerURL(urlString: URL) -> UIImage {
var finalImg = UIImage()
var request = URLRequest(url: urlString)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer " + UserDefaults.standard.string(forKey: "access_token")!, forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error as Any)
return
}
DispatchQueue.main.async(execute: { () -> Void in
print(data?.count)
finalImg = UIImage(data: data ?? Data()) ?? UIImage(systemName: "AppIcon")!
})
}).resume()
return finalImg
}
但我在这一行有问题:
finalImg = UIImage(data: data ?? Data()) ?? UIImage(systemName: "AppIcon")!
我通常会收到这样的错误:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
首先我认为我有nil
数据,但在检查后.count
我发现数据不是空的。所以我认为问题出在某个地方UIImage
,为了解决它,我尝试添加这样的处理?? UIImage(systemName: "AppIcon")!
,但它并没有解决我的崩溃问题。也许有人会看到问题出在哪里。
PS如果我没有发布一些重要信息,请在评论中告诉我,我会编辑我的问题。谢谢 :)