I'm learning iOS programming by following this wonderful tutorial, except I'm targeting iOS 9 and make some small modifications.
In the tableView() function below, I can get thumbnail image downloaded and my handlers invoked, as evident from the console print out of the two logging lines. However, when the app is running (in simulator), I have to click on each table cell to get the image to show up. I tried to see if there is a refresh()
or something like that in the UIImageView
or the table cell, but found nothing.
How to make the image show up immediately as the data is received?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
let album = self.albums[indexPath.row]
// ... setting up other cell's data, see the tutorial link
// Start by setting the cell's image to a static file
// Without this, we will end up without an image view!
cell.imageView?.image = UIImage(named: "Blank52")
let request: NSURLRequest = NSURLRequest(URL: thumbnailURL)
let urlSession = NSURLSession.sharedSession()
urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
print("received thumbnail \(thumbnailURLString)") // reached
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data!)
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
print("...dispatched thumbnail image for \(thumbnailURLString)") // reached
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
}).resume()
return cell
}
I figured out a work around. If I also update the text slight, the image shows up right the way without clicking on the table view cell.
cellToUpdate.imageView?.image = image
cellToUpdate.textLabel?.text = "\(album.title) " // a space is added to the end to make a difference and force the cell to be updated
Sounds like a bug in UITableViewCell
(or the simulator? haven't tried on a real device) to me.