0

I have a UITableView, I use the cellForRowAtIndexPath: function to download an image for a specific cell. The image download is performed asynchronously and finishes after a short amount of time and calls a completion block after finishing. I set the cell content to the downloaded image inside the completion block, but it doesn't get updated until after the user finishes scrolling. I know that the reason is because the code should be running in NSRunLoopCommonModes, but I don't know how to do that in this case, any help is appreciated.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let dequeued  = self.tableView.dequeueReusableCellWithIdentifier(imageFileCellIdentifier)
        let cell = dequeued as! ImageTableViewCell

    source.FetchImage(imageLocation, completion: { (image) in
        dispatch_async(dispatch_get_main_queue(), { 
            cell.previewImage.image = image
            cell.previewImage.contentMode = .ScaleAspectFill
        }
    })
}

2 Answers2

1

try this

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let dequeued  = self.tableView.dequeueReusableCellWithIdentifier(imageFileCellIdentifier)
        let cell = dequeued as! ImageTableViewCell

    source.FetchImage(imageLocation, completion: { (image) in

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
             cell.previewImage.image = image
             cell.previewImage.contentMode = .ScaleAspectFill
        })


    })
}
Hieu Dinh
  • 692
  • 5
  • 18
0

UI must be updated in main thread

You can use something like this to update imageView - coz asynchronous completion block may not call within main thread.

dispatch_async(dispatch_get_main_queue(), {
    cell.previewImage.image = image
    cell.previewImage.contentMode = .ScaleAspectFill
} 

to update UIs

And also it is better if you check that the cell you are updating is the correct cell. Because when download completed(asynchronously) cell may be scrolled-out of the view and that cell may be allocated to another row. In that case you are setting the image to a wrong cell.

eg.

if cell.imageName == 'downloaded_image_name' {
    // do update
}
RJE
  • 781
  • 6
  • 14