Search code examples
iosswiftalamofire

Display image in cell.imageView.image using URL


I'm trying to display image once it's been processed. Here's my code.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
        let dict = itemsArray?[indexPath.row]


        cell.textLabel?.text = dict?["food_name"] as? String
        var URLz = dict?["image_url"] as! String
        Alamofire.request(URLz).response{ response in
            if let data = response.data{
                let image = UIImage(data:data)
                cell.imageView?.image = image
            }else{
                print("Data is nil.")
            }
        }





        return cell;
    }

When I do the following; nothing gets displayed but table rows.


Solution

  • It's not trivial to download and show image in tableviewcell, you need to check if the cell is visible before assigning the image to the imageview.

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
                .............
                cell.imageView?.image = UIImage(named: "placeholder.png") //or nil
                if let dict = dict, imageURL = dict["image_url"] as? String {
                    Alamofire.request(imageURL).response { response in
                        if let data = response.data, let image = UIImage(data: data) {
                            DispatchQueue.main.async {
                                if let cell = tableView.cellForRow(at: indexPath) {
                                     cell.imageView?.image = image
                                }
                            }
                        } else {
                            print("Data is nil.")
                        }
                    }
                }
                return cell
        }
    

    Better option would be to use third party libraries like Kingfisher which uses UIImageView extension to download and cache images from the network. It would as simple as below

    let url = URL(string: imageURL)!
    cell.imageView.kf.setImage(with: url, placeholder: nil)