Adin Ljudina
Adin Ljudina

Reputation: 185

How to load an image from URL and display it in tableView cell (Swift 3)

I have the image URL and I want to display that image in UIImageView which is placed in a tableView cell. I created a custom cell and added an outlet for the imageView. Since I am loading news the URL changes accordingly. NOTE: I am using Alamofire to process my HTTP requests.

struct News {
    let title: String
    let text: String
    let link: String
    let imgUrl: String

    init(dictionary: [String:String]) {
        self.title = dictionary["title"] ?? ""
        self.text = dictionary["text"] ?? ""
        self.link = dictionary["link"] ?? ""
        self.imgUrl = dictionary["imgUrl"] ?? ""
    }
}

And loading info to my custom cell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
    let news = newsData[indexPath.row]
    cell?.headline.text = news.title
    cell?.excerpt.text = news.text
    cell?.thumbnailImage.text = news.imgUrl
    return cell!
 }

Upvotes: 1

Views: 14949

Answers (4)

Sandip Gill
Sandip Gill

Reputation: 1100

You can use this code to get image from url and can set a placeholder image as well. for example:-

cell.imageView?.imageFromServerURL(urlString:  "urlString", PlaceHolderImage: UIImage.init(named: "imagename")!)
 
extension UIImageView {
   
 public func imageFromServerURL(urlString: String, PlaceHolderImage:UIImage) {
        
        if self.image == nil{
              self.image = PlaceHolderImage
        }
        
        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
            
            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                self.image = image
            })
            
        }).resume()
    }}

Upvotes: 8

stackich
stackich

Reputation: 5217

I used a Kingfisher library

import Kingfisher

tableViewCell class:

class MyCell: UITableViewCell {
    
    @IBOutlet weak var cellImg: UIImageView!
    
    @IBOutlet weak var cellLbl: UILabel!
    
}

Assign this class to your cell in storyboard

And finally, do this in CellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")! as! MyCell
        let url = URL(string: "https://files.pitchbook.com/website/files/jpg/food_delivery_800.jpg")
        cell.cellImg.kf.setImage(with: url)
        return cell
    }

That's it

Upvotes: 1

Matloob Hasnain
Matloob Hasnain

Reputation: 1037

Please Use SDWebImage. It's an imageview category that downloads the image in the background without freezing your UI, and also provides caching as well. You can set a placeholder image as well. Placeholders show until your actual image is downloaded. After downloading, the actual image in your cell's Imageview is updated automatically, and you don't need to use any completion handler.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
    let news = newsData[indexPath.row]
    cell?.headline.text = news.title
    cell?.excerpt.text = news.text
    cell?.thumbnailImage.sd_setImageWithURL(NSURL(string: news.imgUrl), placeholderImage:UIImage(imageNamed:"placeholder.png"))
    return cell!
}

Upvotes: 0

TajyMany
TajyMany

Reputation: 537

This becomes quite easy, as you're using Alamofire. Unlike @Mochi's example, this won't block the interface.

Here's an example:

Alamofire.request(news.imgUrl).response { response in
    if let data = response.data {
        let image = UIImage(data: data)
        cell?.thumbnailImage.image = image
    } else {
        print("Data is nil. I don't know what to do :(")
    }
}

*Please note I wasn't able to test this before I answered. You may need to tweak this code a bit.

Upvotes: 1

Related Questions