0

I am developing a small application. I've been searching for days but couldn't find a suitable answer for myself. The API I use has a png path that comes as a string. I want to show this in imageView. Can anyone help?

My model class is as follows:

import Foundation

struct BooksModel: Codable {
    let data: [Book]

    enum CodingKeys: String, CodingKey {
        case data
    }
}

struct Book: Codable {
    let _id: Int
    let name: String
    let imageUrl: String
}

I want to show inside Cell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell
    
    if filteredBook.isEmpty {
        cell.bookTitle.text = contents[indexPath.row].name
    } else {
        cell.bookTitle.text = filteredBook[indexPath.row].name
    }
    //cell.bookImage.image = UIImage(named: contents[indexPath.row].imageUrl)
    return cell
}
  • `UIImage(named:)` won't load an image from a URL. If the URL is a file URL you can convert it to a path and use `init(contentsOfFile:)` If the URL comes from an API, though, it is likely that the URL points to a remote image. In that case you need to download the data asynchronously using URLSession and convert it to an image once the download is complete. – Duncan C Jul 29 '22 at 12:13
  • DispatchQueue.global().async { let data = try? Data(contentsOf: URL(string: “”https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fcdn.pixabay.com%2Fphoto%2F2017%2F06%2F30%2F11%2F17%2Ftree-2458047_960_720.png&f=1&nofb=1)) DispatchQueue.main.async { if let imageDate = data{ imageView.image = UIImage(data: data!) } } } Hope it helps – user2094867 Jul 29 '22 at 13:00
  • You will need to use path url then a file url for showing in UIImage view. eg. like this sample path url showing the image https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fcdn.pixabay.com%2Fphoto%2F2017%2F06%2F30%2F11%2F17%2Ftree-2458047_960_720.png&f=1&nofb=1 then download this image asynchronously and show in UIImage view see above code. hope it helps.. – user2094867 Jul 29 '22 at 13:02

0 Answers0