1

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!
 }
Duncan C
  • 128,072
  • 22
  • 173
  • 272
Adin Ljudina
  • 185
  • 2
  • 5
  • 15
  • 1
    possible duplicate http://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift/27712427#27712427 – Leo Dabus Jan 09 '17 at 23:24
  • @LeoDabus suggested a good post. But since you are already using Alamofire, the easiest way would be to install https://github.com/Alamofire/AlamofireImage library and use the below syntax to show image. This takes care of asynchronous loading and all. `cell?.thumbnailImage.af_setImage(withURL: )` – Bhavik Bhagat Jan 10 '17 at 01:09

4 Answers4

8

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()
    }}
Grimthorr
  • 6,856
  • 5
  • 41
  • 53
Sandip Gill
  • 1,060
  • 1
  • 11
  • 22
1

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.

TajyMany
  • 527
  • 7
  • 20
1

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

stackich
  • 3,607
  • 3
  • 17
  • 41
0

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!
}
TajyMany
  • 527
  • 7
  • 20
Matloob Hasnain
  • 1,025
  • 6
  • 21