简体   繁体   中英

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!
 }

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

cell.imageView?.imageFromURL(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()
    }}

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.

I used a Kingfisher library
Here are few easy steps to use the 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

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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM