Skip to content

Commit 0942319

Browse files
committed
Fast image loading using async NSURLRequest
1 parent 9e147fa commit 0942319

File tree

1 file changed

+30
-21
lines changed

1 file changed

+30
-21
lines changed

TestSwift/SearchResultsViewController.swift

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -58,30 +58,39 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
5858
// If the image does not exist, we need to download it
5959
var imgURL: NSURL = NSURL(string: urlString)
6060

61-
println("Download the image \(imgURL)")
6261
// 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-
}
62+
var request: NSURLRequest = NSURLRequest(URL: imgURL)
63+
var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)
64+
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
65+
if !error? {
66+
//var imgData: NSData = NSData(contentsOfURL: imgURL)
67+
image = UIImage(data: data)
68+
69+
// Store the image in to our cache
70+
self.imageCache.setValue(image, forKey: urlString)
71+
cell.image = image
72+
73+
dispatch_async(dispatch_get_main_queue()) {
74+
// Back on the main thread, let's set the image view of the cell to use our amazing new image
75+
// First, we need to make sure the cell hasn't gone off the screen, or worse, been re-used
76+
// Validate the cell is still available by using cellForRowAtIndexPath
77+
var sCell: UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)
78+
79+
// If the cell exists, we're good and we can update it with this image
80+
if sCell? {
81+
let pCell: UITableViewCell = sCell!
82+
pCell.image = image
83+
}
84+
}
85+
}
86+
else {
87+
println("Error: \(error.localizedDescription)")
88+
}
89+
})
90+
8391
}
8492

93+
8594
})
8695

8796
tableView.indexPathForCell(cell)

0 commit comments

Comments
 (0)