@@ -40,30 +40,40 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
40
40
var formattedPrice : NSString = rowData [ " formattedPrice " ] as NSString
41
41
42
42
dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ) , {
43
+ // Jump in to a background thread to get the image for this item
43
44
44
45
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
45
46
var urlString : NSString = rowData [ " artworkUrl60 " ] as NSString
46
- //var image: UIImage? = self.imageCache[urlString] as? UIImage
47
+
48
+ // Check our image cache for the existing key. This is just a dictionary of UIImages
47
49
var image : UIImage ? = self . imageCache. valueForKey ( urlString) as? UIImage
50
+
48
51
if ( !image? ) {
52
+ // If the image does not exist, we need to download it
49
53
var imgURL : NSURL = NSURL ( string: urlString)
50
54
55
+ println ( " Download the image \( imgURL) " )
51
56
// Download an NSData representation of the image at the URL
52
57
var imgData : NSData = NSData ( contentsOfURL: imgURL)
53
58
image = UIImage ( data: imgData)
59
+
60
+ // Store the image in to our cache
54
61
self . imageCache. setValue ( image, forKey: urlString)
55
- // self.imageCache[urlString] = image
62
+
63
+ println ( " Image downloaded " )
56
64
}
57
65
dispatch_async ( dispatch_get_main_queue ( ) ) {
66
+ // Back on the main thread, let's set the image view of the cell to use our amazing new image
67
+ // First, we need to make sure the cell hasn't gone off the screen, or worse, been re-used
68
+ // Validate the cell is still available by using cellForRowAtIndexPath
58
69
var sCell : UITableViewCell ? = tableView. cellForRowAtIndexPath ( indexPath)
59
- if sCell != nil {
70
+
71
+ // If the cell exists, we're good and we can update it with this image
72
+ if sCell? {
60
73
let pCell : UITableViewCell = sCell!
61
74
pCell. image = image
62
- println ( " set cell to \( image? . size. width) " )
63
- cell. image = image
64
-
75
+ println ( " set image " )
65
76
}
66
- println ( " attempt to set cell " )
67
77
}
68
78
69
79
} )
0 commit comments