I have a Chat Log which is simply a UICollectionView
. Every sell has an avatar (UIImage
) and a text bubble. I'm trying to fill avatars with proper images by fetching avatars URL from the server with Alamofire like this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "chatMessage", for: indexPath) as! ChatMessageCell
let imageURL = URL(string: messagesArray![indexPath.item].userAvatar)
Alamofire.download(imageURL!).responseData { response in
if let data = response.result.value {
cell.userAvatar.image = UIImage(data: data)
}
}
cell.messageText.text = messagesArray![indexPath.item].userText
}
My problem: In some cells avatar appears in some is not. I think it's related to Alamofire async work. So my question is how to fill images to UICollectionView
properly to show each avatar in each cell?
I think it's better to use SDWebImage , as according to your current implementation image fetching happens multiple times
imageView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
here SDWebImage