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

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

        if error != nil {
            print(error ?? "")
        //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)

Posted 5 months ago | reported 5 months ago
Posted by Kenny Ho (1)

Caught by 3 reasons: