Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableViewCell ImageView shows always different data

I have a chat and want to display the users profile pictures. Everything will be displayed correctly but not the profile pictures of the users. Everytime, when I reload my view, I get other pictures.

I load the Profileimage in with the following lines:

func showProfilImage(uid: String, completion: @escaping (UIImage) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil, let data = data, let image = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    let finishedImage = image.withRenderingMode(.alwaysOriginal)
                    completion(finishedImage)
                }
                }.resume()
    }
}

Then I call showProfilImage in cellForRowAt with the following lines:

self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (image) in
    cell.profilePic.image = image
}

UPDATE

Now i implemented sdWebImage and make a completion with the URL:

func showProfilImage(uid: String, completion: @escaping (URL) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }
        completion(url)
    }
}

Here I call my showProfilImage:

self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (url) in
            cell.profilePic.image = nil
            cell.profilePic.sd_setImage(with: url, completed: { (_, _, _, _) in
            })
        }
like image 629
jo1995 Avatar asked Sep 03 '26 06:09

jo1995


1 Answers

Your current code has dequeuing and no cashing problems and the right for that is to use SDWebImage

cell.profilePic.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "placeholder.png"))

also something like

UserApi.shared.observeUser(uid: uid) { (user) in

would be once say in viewDidLoad

like image 120
Sh_Khan Avatar answered Sep 07 '26 09:09

Sh_Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!