Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jquave/02091c80761b780168ec to your computer and use it in GitHub Desktop.
Save jquave/02091c80761b780168ec to your computer and use it in GitHub Desktop.
JamesonQuave.com iOS 8 Swift Tutorial Part 6 cellForRowAtIndexPath
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell
// Find this cell's album by passing in the indexPath.row to the subscript method for an array of type Album[]
let album = self.albums[indexPath.row]
cell.text = album.title
cell.image = UIImage(named: "Blank52")
cell.detailTextLabel.text = album.price
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
// Jump in to a background thread to get the image for this item
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
//var urlString: NSString = rowData["artworkUrl60"] as NSString
let urlString = album.thumbnailImageURL
// Check our image cache for the existing key. This is just a dictionary of UIImages
var image: UIImage? = self.imageCache[urlString!]
if( !image? ) {
// If the image does not exist, we need to download it
let imgURL: NSURL = NSURL(string: urlString)
// Download an NSData representation of the image at the URL
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if !error? {
image = UIImage(data: data)
// Store the image in to our cache
self.imageCache[urlString!] = image
// Sometimes this request takes a while, and it's possible that a cell could be re-used before the art is done loading.
// Let's explicitly call the cellForRowAtIndexPath method of our tableView to make sure the cell is not nil, and therefore still showing onscreen.
// While this method sounds a lot like the method we're in right now, it isn't.
// Ctrl+Click on the method name to see how it's defined, including the following comment:
/** // returns nil if cell is not visible or index path is out of range **/
if let albumArtsCell: UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath) {
albumArtsCell!.image = image
}
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
else {
cell.image = image
}
})
return cell
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment