How to use NSCache and download Image From Url and Show images in CollectionViewCell?

552 Views Asked by At

I have a UICollectionViewCell and Inside that there is a imageView. My requirement is that I am getting Images Url from My_API and I want to download the Images from these Images Url and want to show them into a collectionViewCell imageView.

First thing is that how can I download the images from url I mean Which method is best and how to use NSCache in CollectionViewCell for images (in CellForRowAtIndexPath method).

Here is my code:

//MARK : DataSource

extension BrandImagesTableCell : UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if 0 != arrImages.count {
        return self.arrImages.count
    }

    return 0
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BrandImagesCell", for: indexPath) as! BrandImagesCell

    //let StrUrl = NSURL(string: self.arrImages[indexPath.row])! as URL
    let urlPath: String = self.arrImages[indexPath.row]
    let StrUrl: NSURL = NSURL(string: urlPath)!

    if 0 != arrImages.count
    {
        cell.brandImage.downloadedFrom(url: StrUrl as URL)//, contentMode: .scaleToFill)
        //cell.backgroundColor = UIColor.lightGray
    }

    return cell
 }
} 

In self.arrImages I have Images url.

And here is my download image method:

//Download Image from server.

extension UIImageView {
 func downloadedFrom(url: URL) { //, contentMode mode: UIViewContentMode = .scaleAspectFit) {
    //contentMode = mode
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { () -> Void in
            self.image = image
        }
        }.resume()
  }
}  

So I want to know which method is better to download images, and do I have to use thread or NSCache?

2

There are 2 best solutions below

16
On

Use KingFisher download this library and add into your project.

Use code like :

let ProfileUrl = YOUR_URL! as! String
if ProfileUrl.isEmpty == true {
        YOURIMAGE_VIEW.image = UIImage.init(named: "ic_default_IMAGE.png")
}else{
        let fbUrl = NSURL(string: ProfileUrl )!
         YOURIMAGE_VIEW.kf_setImageWithURL(fbUrl, placeholderImage: nil,
                                        optionsInfo: [.Transition(ImageTransition.Fade(1))],
                                        progressBlock: { receivedSize, totalSize in

            },
            completionHandler: { image, error, cacheType, imageURL in
                                            print("Finished")
        })

    }

Retrive image from cache file

KingfisherManager.sharedManager.retrieveImageWithURL(url, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in
    print(image)
})
0
On

Using Swift 3 :-

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BrandImagesCell", for: indexPath) as! BrandImagesCell

    //let StrUrl = NSURL(string: self.arrImages[indexPath.row])! as URL
    let urlPath: String = self.arrImages[indexPath.row]
    //let StrUrl: NSURL = NSURL(string: urlPath)!

    if 0 != arrImages.count
    {
        let imgUrl = urlPath

        //Add Default image
        if imgUrl.isEmpty == true {
            cell.brandImage.image = UIImage.init(named: "placeholder.png")
        }

        else
        {
            let url = URL(string: imgUrl)!
             cell.brandImage.kf.setImage(with: url,
                                  placeholder: nil,
                                  options: [.transition(.fade(0.5))],
                                  progressBlock: { receivedSize, totalSize in
                                  print("\(indexPath.row + 1): \(receivedSize)/\(totalSize)")
                                },

                                  completionHandler: { image, error, cacheType, imageURL in
                                    print("Finished")
                                    //print("\(indexPath.row + 1): Finished")
                                })
        }
    }

    return cell
}