直到滚动,CollectionViewCell图像才会显示

问题描述:

我正在使用此代码将图像显示到我的customCell中. 是我的代码,用于从API提取图像.根据给定的链接,它工作正常.但是,当我将此代码添加到图像缓存的cellForItemAt indexPath:中时,问题开始了.

I am using this code to display image in to my customCell. This is my code to fetch image from API. It was working fine as per the given link. But the problem started when I added this code to my cellForItemAt indexPath: for image Cache.

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

    // Displaying other elements with text

    customCell.mainImage.image = nil

    var image1 = self.imageCache.object(forKey: indexPath.item as AnyObject) as? UIImage

        if (image1 == nil) {
            self.ImageFetcher(postId: self.myArray[indexPath.item].id!, completion: { (image) in
            image1 = image
            self.imageCache.setObject(image1!, forKey: indexPath.item as AnyObject)
        })
    }
    DispatchQueue.main.async {
        customCell.mainImage.image = image1
    }
}

上面的代码工作正常,没有任何错误,但是直到我上下滚动collectionView时,才显示/加载图像.不明白我在这里想念的是什么.任何帮助,将不胜感激 !!

Above code works fine without any error but, not displaying/loading images until I scroll the collectionView up and down. Don't understand what I am missing here. Any help would be appreciated !!

STEP:1创建uiimageview扩展名以从url下载图像,如果已经下载则从缓存下载

STEP:1 Create extension of uiimageview to download image from url, and if already downloaded then from cache

   let imageCache = NSCache()
    extension UIImageView {

    func loadImageUsingCacheWithURLString(url: NSURL) {

        self.image = nil

        // First check if there is an image in the cache
        if let cachedImage = imageCache.objectForKey(url) as? UIImage {

            self.image = cachedImage

            return
        }

        else {
        // Otherwise download image using the url location in Google Firebase
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in

            if error != nil {
                print(error)
            }
            else {
                dispatch_async(dispatch_get_main_queue(), {

                    // Cache to image so it doesn't need to be reloaded every time the user scrolls and table cells are re-used.
                    if let downloadedImage = UIImage(data: data!) {

                        imageCache.setObject(downloadedImage, forKey: url)
                        self.image = downloadedImage

                    }
                })
            }
            }).resume()
        }

    }

第2步:用法

STEP 2 : Usage

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

    // Displaying other elements with text
    customCell.mainImage.loadImageUsingCacheWithURLString(url: yoururl)
 }