Search code examples
swiftdispatch-async

Image loading lag in tableview with RSS feed datasource in Swift


I am using dispatch_async to download the images from an rss feed to avoid lagging but when I scroll fast, I can see the images are changing, which is pretty annoying. How can I avoid that?

Here is my code:

let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
    dispatch_async(backgroundQueue, {
        let url = NSURL(string: fImage)
        let data = NSData(contentsOfURL: url!)
        dispatch_async(dispatch_get_main_queue(), { 
            if data != nil {
                self.thumbnailIMG.image = UIImage(data: data!)!
            } else {
                self.thumbnailIMG.image = UIImage(named: "logo_new2")!
            }

         })

     })

Solution

  • Try it this way :

    import UIKit
    
    class ViewController: UIViewController {
    
    @IBOutlet weak var thumbnailIMG: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.thumbnailIMG.image = UIImage(named: "logo_new2")
        if let checkedUrl = NSURL(string: "http://staging.api.cheapeat.com.au/restaurants/1/photo") {
            downloadImage(checkedUrl)
        }
    }
    func downloadImage(url:NSURL){
    
        getDataFromUrl(url) { data in
            dispatch_async(dispatch_get_main_queue()) {
    
                self.thumbnailIMG.image = UIImage(data: data!)
            }
        }
    }
    
    func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {
        NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in
            completion(data: NSData(data: data))
            }.resume()
        }
    }
    

    This is not lagging for me.

    May be this will help you too.