Abhinav Abhinav -4 years ago 503
Swift Question

Alamofire Image : Placeholder image is not set for af_setImageWithURL

I am using

Alamofire API to fetch the table cell images and pass a default placeholder image:

let defaultImage = UIImage(named:"myImage")
cell.imageView.af_setImageWithURL(imageURL, placeholderImage:defaultImage, imageTransition: .CrossDissolve(0.1))

Problem: When my image does not exists at the downloading path, cell do not show the default image as well. When I scroll the table up & down (to purge and re-use the same cell) then it shows up.


Noticed this is happening after dequeuing the cell, I reset the image first and then call Alamofire. If I comment out below line, it works fine but then I am running into a risk of showing old product image if both image URL and default images are not available.

cell.imageView.image = nil

Anybody faced similar issue, please advise.

Answer Source

You need to make sure you cancel your request and also nil out the image in prepareForReuse. Otherwise you can run into a few different problems. Here's the ImageCell class in the iOS Example in AFI.

class ImageCell: UICollectionViewCell {
    class var ReuseIdentifier: String { return "org.alamofire.identifier.\(type(of: self))" }
    let imageView: UIImageView

    // MARK: - Initialization

    override init(frame: CGRect) {
        imageView = {
            let imageView = UIImageView(frame: frame)

            imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            imageView.contentMode = .center
            imageView.clipsToBounds = true

            return imageView

        super.init(frame: frame)


        imageView.frame = contentView.bounds

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

    // MARK: - Lifecycle Methods

    func configureCell(with URLString: String, placeholderImage: UIImage) {
        let size = imageView.frame.size

            withURL: URL(string: URLString)!,
            placeholderImage: placeholderImage,
            filter: AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: 20.0),
            imageTransition: .crossDissolve(0.2)

    override func prepareForReuse() {

        imageView.image = nil


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download