loading tableView images asynchronously in swift

前端 未结 1 1705
我在风中等你
我在风中等你 2021-01-06 13:41

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

相关标签:
1条回答
  • 2021-01-06 14:11

    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")
    
    0 讨论(0)
提交回复
热议问题