Check that the cell is still visible after download
suggest changeSometimes the download takes longer than the cell stays on screen. The downloaded image can then appear on the wrong cell. Avoid the UIImageView extension for this case and set the image in the completion handler instead.
The sample assumes a table view whose cell has an image view, and that this code runs in tableView(_:cellForRowAt:), where imageView, tableView, and indexPath are in scope. responseImage comes from AlamofireImage. UIImage(named:) is force-unwrapped, so a missing placeholder image crashes.
let placeholderImage = UIImage(named: "placeholder")!
imageView.image = placeholderImage
let url = URL(string: "https://httpbin.org/image/png")!
Alamofire.request(url, method: .get).responseImage { response in
guard let image = response.result.value else { return }
if let updateCell = tableView.cellForRow(at: indexPath) {
updateCell.imageView.image = image
}
}
The image view starts as the placeholder. Alamofire requests the URL with .get, and responseImage decodes the body as an image.
When the closure runs, it returns immediately if decoding failed. cellForRow(at:) returns a cell only while that row is visible. If the user has scrolled the row off screen, updateCell is nil and the image is left unset, so a reused cell does not show this download.