如何使用NSCache并从URL下载图像并在CollectionViewCell中显示图像?

时间:2017-01-09 08:35:25

标签: ios swift download nscache

我有一个UICollectionViewCell和Inside有一个imageView。我的要求是我从My_API获取Images Url,我想从这些图像Url下载图像,并希望将它们显示到collectionViewCell imageView中。

首先,我如何从url下载图像?我的意思是哪种方法最好,以及如何在CollectionViewCell中使用NSCache图像(在CellForRowAtIndexPath方法中)。

这是我的代码:

// 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
 }
} 

在self.arrImages我有图片网址。

这是我的下载图片方法:

//从服务器下载图片。

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()
  }
}  

所以我想知道哪种方法更适合下载图像,我是否必须使用线程或NSCache?

2 个答案:

答案 0 :(得分:0)

使用KingFisher下载此库并添加到您的项目中。

使用以下代码:

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")
        })

    }

从缓存文件中恢复图像

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

答案 1 :(得分:0)

使用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
}