Lazy loading of images using Alamofire and AlamofireImage Not working at first Load

Viewed 938

So I am trying to follow the mvc architecture in this app. Here is the code for the image part.

Model

   import Alamofire
   import AlamofireImage

    class Brands {
    private var _image : UIImage!
    var image : UIImage {
        if _image == nil {
           _image = UIImage(named: "loadingImage")
        }
        return _image
    }

    init(BrandsDict : Dictionary<String, AnyObject>){
      if let imageUrl = BrandsDict["imageUrl"] as? String{
         Alamofire.request(imageUrl).responseImage(completionHandler: { (response) in
                    guard let image = response.result.value else {
                        self._image = UIImage(named: "loadingImage")
                        return
                    }
                    self._image = image

                 })
       }else {
       self._image = UIImage(named : "loadingImage")
    }

View

class BrandsCVCell : UICollectionViewCell {
  @IBOutlet weak var BrandImage : UIImageView!

  var brand : Brands!

  func configureCell(_ brand : Brands){
   self.brand = brand
   BrandImage.image = self.brand.image
}
}

Controller

inViewDidLoad ....

if let jsonArray = data as? NSArray {
                for objects in jsonArray {
                    let Brand = Brands(BrandsDict: objects as! Dictionary<String, AnyObject>)
                    self.Brands.append(Brand)
                }
               self.bestBrandCollection.reloadData()
            }

....

if collectionView == BrandCollection {
 if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BrandsCell", for: indexPath) as? BrandCollectionViewCell {

                let Brand = Brands[indexPath.row]
                cell.configureCell(Brand)
                return cell
            }else {
                return UICollectionViewCell()
            }
}

The problem is that when the images are loaded in the collection view the cells which are in display does not get the downloaded images but when i scroll them the earlier cells get their images. Can somebody help me to lazy load the images after they are downloaded. (maybe completion handler but i don't know where to put it). Coded answers will be appreciated.

1 Answers
Related