0

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)
    }
}
kkakkurt
  • 2,790
  • 1
  • 30
  • 33
  • Add the JSON example you're getting. – PGDev May 17 '19 at 10:09
  • You need to get image data from url first then convert data to UIImage and assign to imageview. – Pravin May 17 '19 at 10:10
  • [{ "albumId": 1, "id": 1, "title": "accusamus beatae ad facilis cum similique qui sunt", "url": "https://via.placeholder.com/600/92c952", "thumbnailUrl": "https://via.placeholder.com/150/92c952" }, { "albumId": 1, "id": 2, "title": "reprehenderit est deserunt velit ipsam", "url": "https://via.placeholder.com/600/771796", "thumbnailUrl": "https://via.placeholder.com/150/771796" }] – vindeep venu May 17 '19 at 10:13
  • you should have check this tutorial. https://grokswift.com/uitableviewcell-images-from-api/ – Akash Soni May 17 '19 at 10:30

3 Answers3

1

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.

NikR
  • 628
  • 4
  • 14
0

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.

PGDev
  • 23,751
  • 6
  • 34
  • 88
0

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)

}
Vishal Parmar
  • 615
  • 4
  • 31
Pratik
  • 676
  • 10
  • 9