My code download images from the web and sets them as a tableView cell imageView. It works fine except that I need to tap on a cell for it to refresh the cell\'s content and
Use the following class:
class ImageLoadingWithCache {
var imageCache = [String:UIImage]()
func getImage(url: String, imageView: UIImageView, defaultImage: String) {
if let img = imageCache[url] {
imageView.image = img
} else {
let request: NSURLRequest = NSURLRequest(URL: NSURL(string: url)!)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)
self.imageCache[url] = image
dispatch_async(dispatch_get_main_queue(), {
imageView.image = image
})
}
else {
imageView.image = UIImage(named: defaultImage)
}
})
}
}
}
Usage:
var cache = ImageLoadingWithCache()
cache.getImage(YOUR_URL, imageView: YOUR_IMAGEVIEW, defaultImage: "DEFAULT_IMAGE_NAME")