0

I'm trying to cache images from a URL to make my table scroll more smoothly. This doesn't seem to be caching them and I can't figure out what I'm doing wrong. Can anyone tell me what's wrong with this?

let imageCache = NSCache()

extension UIImageView {

    func loadImageUsingCacheWithUrlString(urlString: String) {

        self.image = nil

        //check cache for image first
        if let cachedImage = imageCache.objectForKey(urlString) as? UIImage {
            self.image = cachedImage
            return
        }

        //otherwise fire off a new download
        let url = NSURL(string: urlString)
        NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in

            //download hit an error so lets return out
            if error != nil {
                print(error)
                return
            }

            dispatch_async(dispatch_get_main_queue(), {

                if let downloadedImage = UIImage(data: data!) {
                    imageCache.setObject(downloadedImage, forKey: urlString)

                    self.image = downloadedImage
                }
            })

        }).resume()
    }
}

I feel like there should be an else { before firing off the new download, but even when I tried that I don't think it was working right. I even tried running it this way, scrolling through the table to make sure it has a chance to cache all the images, then deleting the whole download part so that it will only load cached images, and no images showed up so I don't think it's actually caching them.

Wayne Filkins
  • 494
  • 6
  • 20

1 Answers1

0

Ok well sorry if it was a bad question. This is what finally worked:

var imageCache = NSMutableDictionary()

extension UIImageView {

    func loadImageUsingCacheWithUrlString(urlString: String) {

        self.image = nil

        if let img = imageCache.valueForKey(urlString) as? UIImage{
            self.image = img
        }
        else{
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in

                if(error == nil){

                    if let img = UIImage(data: data!) {
                        imageCache.setValue(img, forKey: urlString)    // Image saved for cache
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.image = img
                    })
                    }


                }
            })
            task.resume()
        }
    }
}

I guess I had something out of order or something.

Wayne Filkins
  • 494
  • 6
  • 20