TableViewCell ImageView shows always different data

Viewed 48

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
            })
        }
3 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

If you're fetching the image correctly for each user then you problem might be laying in scrolling and dequeuing the cell to solve such issue inside the UITableViewCell custom class use this function to clear out the UIImageView each time a dequeue happens.

override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil  //setting the image to nil  when get dequeued to reuse 
    }

Read more about this function Here

UITableView reuses its views that means when you load an image one time and cell goes out of screen UITableView will bring the cell back to screen for different data source but the image that previously loaded will still presented on the UIImageView add this line of code

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