Search code examples
iosswiftuitableviewurluiimageview

How do I add am image in a TableView from URL


I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!

override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}

Solution

  • Google this cocoapod: SDWebImage

    use this, it is incredible

    Swift:

    import SDWebImage
    
    imageView.sd_setImage(with: URL(string: "url"), placeholderImage: UIImage(named: "placeholder.png"))
    

    In regards to your second question connection your image view, you will need to create a custom cell