Search code examples
swifturluiimageiso

how to load image in swift from URL


I am passing a URL in string format from firebase to load an image, the url gets passed fine but the cell.articleImage.sd_setImage(with: url, placeholderImage: UiImage(named: "issaimage")) isn't returning the picture from the url, just the placeholder image

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell") as? articlesCell else {
            return UITableViewCell()}

        let article = articleArray[indexPath.row]
        let url = URL(string: article.imageURL)!

        cell.articleImage.sd_setImage(with: url, placeholderImage: UIImage(named: "issaimage"))

        cell.configureCell(title: article.ArticleTitle, author: article.author, date: article.date)

        return cell
    }

Solution

  • This code isn't allowing me to use the image variable

    let image = UIImage(data: imageData)
    

    because it's local variable if you want it to be accessible anywhere inside the class it must be an instance variable

    also don't use Data(contentsOf: url) because it blocks main thread , download it in a background queue then show it in the main queue Or simply use SDWebImage after pod installation use

    let url = URL(string: article.imageURL)!
    cell.imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))