0

I've programmatically setup a collection view that should display an image from an API onto a cell. However, once the cells are displayed and data is called the cells remain empty.

Cells returning an empty image view

Current setup

 override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.register(ImageCell.self, forCellWithReuseIdentifier: imageCellId)

    loadImageData(numberOfItems: numberOfItems)
    
}
   func loadImageData(numberOfItems: Int) {
     client.getImageData(items: numberOfItems, completion: { (error,data) in
        if error != nil {
            print("Error parsing image data")
        } else {
            self.per_page = data.perPage
            self.total_results = data.totalResults
            self.images = data.photos
           
            for image in self.images {
                self.userNameArray.append(image.photographer)
                self.urlArray.append(image.url)
                
            }
            self.imageLinkArray = self.urlArray
        
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    })
}

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellId, for: indexPath) as! ImageCell
        let imageString = String(imageLinkArray[indexPath.row])
        let url = URL(string: imageString)
        let data = try? Data(contentsOf: url!)
        
        if let imageData = data {
            let imageFromDatabase = UIImage(data: imageData)
            cell.imageView.image = imageFromDatabase
        }
        
        return cell
}

Tried:

1 Answers1

0

You should use Kingfisher as an image caching library

https://github.com/onevcat/Kingfisher

First, add the pod to your project: pod 'Kingfisher'

Replace this:

let url = URL(string: imageString)
    let data = try? Data(contentsOf: url!)
    
    if let imageData = data {
        let imageFromDatabase = UIImage(data: imageData)
        cell.imageView.image = imageFromDatabase
    }

with this

let url = URL(string: imageString)
imageView.kf.setImage(with: url)
grantespo
  • 2,233
  • 2
  • 24
  • 62
  • Thank you for your response but I'm looking for a solution that does not involve 3rd party frameworks. – catpawsonkeyboard Oct 17 '20 at 03:06
  • If I may ask, why not use Kingfisher though? They use MIT License, 17.5k stars on github and have so may cool features for image loading/caching. – grantespo Oct 17 '20 at 03:11
  • I usually try to limit 3rd party libraries in my apps too, but an image caching library is probably the highest priority library you'll use in any app – grantespo Oct 17 '20 at 03:13
  • I will give the documentation a read on their repo. I've heard of Kingfisher before just never took the time to try it. – catpawsonkeyboard Oct 17 '20 at 03:43