因为标题会建议我使用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
}
但是,每次发送消息并重新加载表时,图像会消失,然后重新出现,因为我假设它再次通过所有索引路径。
以下方法用于处理头像的dataSource;
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
}
没有错误及其打印图像尺寸。但是图像没有从占位符图像改变!...
答案 0 :(得分:2)
HORAY!我终于从Docs中找到了......在所有地方。
您必须按照以下方式初步设置现有头像...
所以;
let message = messages[indexPath.item]
添加以下内容。
if avatarImage?.avatarImage == nil {
avatarImage?.avatarImage = SDImageCache.shared().imageFromDiskCache(forKey: message.senderId)
}
然后检查Avatars是否存在,如果没有,请去获取它们!但是将它们设置为现有头像中的密钥。例如(message.senderID)
if image != nil {
manager.imageCache.store(image, forKey: message.senderId)
DispatchQueue.main.async
{
avatarImage!.avatarImage = image
avatarImage!.avatarHighlightedImage = image
}
和Bam!各地的头像。希望这有助于某人!