Skip to content

Commit c057169

Browse files
committed
Part5 Async image cells
1 parent e2ae686 commit c057169

File tree

1 file changed

+34
-8
lines changed

1 file changed

+34
-8
lines changed

TestSwift/SearchResultsViewController.swift

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
1313
var api: APIController = APIController()
1414
@IBOutlet var appsTableView : UITableView
1515
var tableData: NSArray = NSArray()
16+
var imageCache = NSMutableArray()
1617

1718
override func viewDidLoad() {
1819
super.viewDidLoad()
@@ -32,17 +33,42 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
3233
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
3334

3435
cell.text = rowData["trackName"] as String
35-
36-
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
37-
var urlString: NSString = rowData["artworkUrl60"] as NSString
38-
var imgURL: NSURL = NSURL(string: urlString)
39-
40-
// Download an NSData representation of the image at the URL
41-
var imgData: NSData = NSData(contentsOfURL: imgURL)
42-
cell.image = UIImage(data: imgData)
36+
cell.image = UIImage(named: "Icon76")
37+
4338

4439
// Get the formatted price string for display in the subtitle
4540
var formattedPrice: NSString = rowData["formattedPrice"] as NSString
41+
42+
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
43+
44+
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
45+
var urlString: NSString = rowData["artworkUrl60"] as NSString
46+
//var image: UIImage? = self.imageCache[urlString] as? UIImage
47+
var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage
48+
if( !image? ) {
49+
var imgURL: NSURL = NSURL(string: urlString)
50+
51+
// Download an NSData representation of the image at the URL
52+
var imgData: NSData = NSData(contentsOfURL: imgURL)
53+
image = UIImage(data: imgData)
54+
self.imageCache.setValue(image, forKey: urlString)
55+
// self.imageCache[urlString] = image
56+
}
57+
dispatch_async(dispatch_get_main_queue()) {
58+
var sCell: UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)
59+
if sCell != nil {
60+
let pCell: UITableViewCell = sCell!
61+
pCell.image = image
62+
println("set cell to \(image?.size.width)")
63+
cell.image = image
64+
65+
}
66+
println("attempt to set cell")
67+
}
68+
69+
})
70+
71+
tableView.indexPathForCell(cell)
4672

4773
cell.detailTextLabel.text = formattedPrice
4874

0 commit comments

Comments
 (0)