正如标题所示,我使用 JSQMessagesViewController。我希望每个用户都有自己的头像 [UIImage],可以从 FirebaseDatabase 中的 URL 获取此头像并通过以下方式提取它。 SDWebImage。我能把它放进去;
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
let message = messages[indexPath.item]
if let messageID = message.senderId {
rootRef.child("users").child(messageID).observe(.value, with: { (snapshot) in
if let profileURL = (snapshot.value as AnyObject!)!["profileURL"] as! String! {
let profileNSURL: NSURL = NSURL(string: profileURL)!
cell.avatarImageView.sd_setImage(with: profileNSURL as URL)
}
})
}
return cell
}
但是,每次您发送消息并重新加载表时,图像都会消失然后重新出现,因为我假设它再次遍历所有索引路径。
下面有一个方法来处理头像的数据源;
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return ???????????????????????????????????????
}
但似乎无法组织与 cellForItemAt 中相同的逻辑?有人可以帮忙吗?...非常感谢。
更新:- ********************************************** **********************
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let placeHolderImage = UIImage(named: "Circled User Male Filled-25")
let avatarImage = JSQMessagesAvatarImage(avatarImage: nil, highlightedImage: nil, placeholderImage: placeHolderImage)
let message = messages[indexPath.item]
if let messageID = message.senderId {
rootRef.child("users").child(messageID).observe(.value, with: { (snapshot) in
if let profileURL = (snapshot.value as AnyObject!)!["profileURL"] as! String! {
let profileNSURL: NSURL = NSURL(string: profileURL)!
// download avatar image here somehow!?
let manager: SDWebImageManager = SDWebImageManager.shared()
manager.downloadImage(with: profileNSURL as URL!, options: [], progress: { (receivedSize: Int, actualSize: Int) in
print(receivedSize, actualSize)
}, completed: { (image, error, cached, finished, url) in
avatarImage!.avatarImage = image
})
}
})
}
return avatarImage
}
此操作及其打印图像尺寸没有错误。然而图像并没有从占位符图像改变!...
最佳答案
万岁!我终于从文档中弄清楚了......在所有地方。
您必须按如下方式初始设置现有头像...
所以在下面;
let message = messages[indexPath.item]
添加以下内容。
if avatarImage?.avatarImage == nil {
avatarImage?.avatarImage = SDImageCache.shared().imageFromDiskCache(forKey: message.senderId)
}
然后检查头像是否存在,如果不存在,就去获取它们!但将它们设置为现有头像中的 key 。例如(消息.senderID)
if image != nil {
manager.imageCache.store(image, forKey: message.senderId)
DispatchQueue.main.async
{
avatarImage!.avatarImage = image
avatarImage!.avatarHighlightedImage = image
}
还有嘭!到处都是头像。希望这对某人有帮助!
关于swift - JSQMessagesViewController 中使用 SDWebImage 的用户特定头像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864283/