Swift async load image

Detection score: 4.0

<p>I tried doing this but I don't understand why my images aren't caching? This is an extension. Every time I open the app, the images would load but for some reason when I scroll, i lose the images. Then it takes forever for it to load. Please help</p>

<pre><code>//image cache allows user to not have to reload previous photos to help save them data
let imageCache = NSCache&lt;NSString, AnyObject&gt;()

class CustomImageView: UIImageView {

var imageUrlString: String?


func loadImageUsingUrlString(_ urlString: String) {

    imageUrlString = urlString

    let url = URL(string: urlString)

    image = nil

    //check cached images
    if let imageFromCache = imageCache.object(forKey: urlString as NSString) as? UIImage {
        self.image = imageFromCache
        return
    }

    //if not, download image from url
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        if error != nil {
            print(error ?? "")
            return
        }
        //if succeed. dispatch means to get back to main UI thread and get back images to UI
        DispatchQueue.main.async(execute: {

            let imageToCache = UIImage(data: data!)

            //to make sure images don't get mixed up with others
            if self.imageUrlString == urlString {
                self.image = imageToCache
            }

            //store imageToCache into ImageCache, to save user data and increase
            imageCache.setObject(imageToCache!, forKey: urlString as NSString)
        })

    }).resume()
}
</code></pre>
Posted 13 days ago | reported 13 days ago
Posted by Kenny Ho (1)

Caught by 3 reasons: