top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to set image for UIImageView in UITableViewCell in SWIFT

+1 vote
2,076 views

How to set image for UIImageView in UITableViewCell Asynchronously for each cell.

posted Aug 13, 2014 by Shiva

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

To set image asynchronously in UITableViewCell.

// Check our image cache for the existing key. This is just a dictionary of UIImages
    //var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage
    var image = self.imageCache[urlString]


    if( image == nil ) {
        // If the image does not exist, we need to download it
        var imgURL: NSURL = NSURL(string: urlString)

        // Download an NSData representation of the image at the URL
        let request: NSURLRequest = NSURLRequest(URL: imgURL)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            if error == nil {
                image = UIImage(data: data)

                // Store the image in to our cache
                self.imageCache[urlString] = image
                if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    cellToUpdate.imageView.image = image
                }
            }
            else {
                println("Error: \(error.localizedDescription)")
            }
        })

    }
    else {
        dispatch_async(dispatch_get_main_queue(), {
            if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                cellToUpdate.imageView.image = image
            }
        })
    }
answer Aug 13, 2014 by Raju
Similar Questions
0 votes

Is it possible to set multiple return type for function in SWIFT. If yes please provide me syntax .

0 votes

How to set return type for function in SWIFT.

+1 vote

How to declare single parameter which accept multiple values.

0 votes

how to use reusable identifier for table view cell in SWIFT.
In Objective C:

static NSString *identifier = @"mainMenuCell";
    cell =[tableView dequeueReusableCellWithIdentifier:identifier];  

Then how it should be in SWIFT

+1 vote

How to use below code in swift.

[actionBtn addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
...