Garret Kaye Garret Kaye - 20 days ago 6
MySQL Question

How to properly load a picture into a UITableVIew

I'm trying to retrieve a user profile photo like this inside the

cellForRowAtIndexPath
method:

let profileImage = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://website.com/something/somethingelse-pic/\(self.userArray[indexPath.row]).jpg")!)!)


I'm just wondering if there is a better and faster way to do this because this seem to load pretty slow and laggy.

Any help would be appreciated!!

Answer

You can use async to load image from URL

       let request: NSURLRequest = NSURLRequest(URL: imgURL)
       let mainQueue = NSOperationQueue.mainQueue()
       NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
            if error == nil {
                // Convert the downloaded data in to a UIImage object
                let image = UIImage(data: data)
                // Store the image in to our cache
                self.imageCache[urlString] = image
                // Update the cell
                dispatch_async(dispatch_get_main_queue(), {
                    if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                         cellToUpdate.imageView?.image = image
                    }
                })
            }
            else {
                // println("Error: \(error.localizedDescription)")
            }
       })

Ref: http://jamesonquave.com/blog/developing-ios-apps-using-swift-part-5-async-image-loading-and-caching/