@@ -15,6 +15,7 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
15
15
var api : APIController = APIController ( )
16
16
@IBOutlet var appsTableView : UITableView
17
17
var tableData : NSArray = NSArray ( )
18
+ var imageCache = NSMutableArray ( )
18
19
19
20
override func viewDidLoad( ) {
20
21
super. viewDidLoad ( )
@@ -38,17 +39,52 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
38
39
var rowData : NSDictionary = self . tableData [ indexPath. row] as NSDictionary
39
40
40
41
cell. text = rowData [ " trackName " ] as String
41
-
42
- // Grab the artworkUrl60 key to get an image URL for the app's thumbnail
43
- var urlString : NSString = rowData [ " artworkUrl60 " ] as NSString
44
- var imgURL : NSURL = NSURL ( string: urlString)
45
-
46
- // Download an NSData representation of the image at the URL
47
- var imgData : NSData = NSData ( contentsOfURL: imgURL)
48
- cell. image = UIImage ( data: imgData)
42
+ cell. image = UIImage ( named: " Icon76 " )
43
+
49
44
50
45
// Get the formatted price string for display in the subtitle
51
46
var formattedPrice : NSString = rowData [ " formattedPrice " ] as NSString
47
+
48
+ dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ) , {
49
+ // Jump in to a background thread to get the image for this item
50
+
51
+ // Grab the artworkUrl60 key to get an image URL for the app's thumbnail
52
+ var urlString : NSString = rowData [ " artworkUrl60 " ] as NSString
53
+
54
+ // Check our image cache for the existing key. This is just a dictionary of UIImages
55
+ var image : UIImage ? = self . imageCache. valueForKey ( urlString) as? UIImage
56
+
57
+ if ( !image? ) {
58
+ // If the image does not exist, we need to download it
59
+ var imgURL : NSURL = NSURL ( string: urlString)
60
+
61
+ println ( " Download the image \( imgURL) " )
62
+ // Download an NSData representation of the image at the URL
63
+ var imgData : NSData = NSData ( contentsOfURL: imgURL)
64
+ image = UIImage ( data: imgData)
65
+
66
+ // Store the image in to our cache
67
+ self . imageCache. setValue ( image, forKey: urlString)
68
+
69
+ println ( " Image downloaded " )
70
+ }
71
+ dispatch_async ( dispatch_get_main_queue ( ) ) {
72
+ // Back on the main thread, let's set the image view of the cell to use our amazing new image
73
+ // First, we need to make sure the cell hasn't gone off the screen, or worse, been re-used
74
+ // Validate the cell is still available by using cellForRowAtIndexPath
75
+ var sCell : UITableViewCell ? = tableView. cellForRowAtIndexPath ( indexPath)
76
+
77
+ // If the cell exists, we're good and we can update it with this image
78
+ if sCell? {
79
+ let pCell : UITableViewCell = sCell!
80
+ pCell. image = image
81
+ println ( " set image " )
82
+ }
83
+ }
84
+
85
+ } )
86
+
87
+ tableView. indexPathForCell ( cell)
52
88
53
89
cell. detailTextLabel. text = formattedPrice
54
90
0 commit comments