vindeep venu
vindeep venu

Reputation: 33

How to display JSON image on custom cell of tableview in Swift?

I'm new into coding, learning how to parse JSON image into table view able to display the labels but not able to display the image file. How to display it? I used the code given below please check it.

import UIKit

class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

    var dataArray = [[String:AnyObject]]()

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://jsonplaceholder.typicode.com/photos")! //change the url
        let session = URLSession.shared
        var request = URLRequest(url: url)
        request.httpMethod = "GET" //set http method as POST
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            guard error == nil else {
                return
            }

            guard let data = data else {
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {

                    self.dataArray = json as [[String : AnyObject]]
                    DispatchQueue.main.async {
                        self.myTable.reloadData()
                    }
                    print(json)
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 250
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 250
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
        cell.labout.text = String(describing: dataArray[indexPath.row]["id"]!)
        cell.imagethum.image = UIImage(named :dataArray[indexPath.row]["thumbnailUrl"]! as! String)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "story") as? FinalViewController
        var selectedindex = indexPath.row
        vc?.jarray = dataArray
        vc?.selectedindex1 = selectedindex
        self.navigationController?.pushViewController(vc!, animated: true)
    }
}

Upvotes: 0

Views: 2162

Answers (3)

Pratik
Pratik

Reputation: 726

You can try this

We use this SDWebImage pod to load images from URL. This pod provides an async image downloader with cache support.

Example Of SDWebImage as below

 let img1 = savedInspofflineData[indexPath.row].image1
 if img1 == ""{
        //Error        
  }else{
      let imageUrl = URL(string: img1!)!
      cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)

}

Upvotes: 0

NikR
NikR

Reputation: 637

You need to download your image at first. The basic solution is:

    if let url = URL(string: "YOUR_URL") {
         if let data = try? Data(contentsOf: url) {
              cell.imagethum.image = UIImage(data: data)
         }
    }

For more advanced solution take a look on SDWebImage framework ( for example ) - it's beginner-friendly.

Upvotes: 1

PGDev
PGDev

Reputation: 24341

You need to download the image using thumbnailUrl String that you're getting from JSON response.

Replace the implementation of cellForRowAt method with the following code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
    cell.labout.text = String(describing: dataArray[indexPath.row]["id"] ?? "")
    if let urlString = dataArray[indexPath.row]["thumbnailUrl"] as? String, let url = URL(string: urlString) {
        URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
            if let data = data {
                cell.imagethum.image = UIImage(data: data)
            }
        }.resume()
    }
    return cell
}

Also, don't use forced unwrapping (!) so extensively. It might result in crashing the app unnecessarily.

Upvotes: 0

Related Questions