Simran Bhavsar
Simran Bhavsar

Reputation: 13

How do you display JSON API data in a table view?

I am not able to display the JSON data in my table view. I don't know why. I tried to get the JSON data, but I am not able to display it on screen in a table format.

This is the model:

class PastTripsVC: UIViewController {
    var past = [PastRide]()
    @IBOutlet weak var mTable: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let nibCell = UINib(nibName: "PastTableView", bundle: nil)
        mTable.register(nibCell, forCellReuseIdentifier: "cell")
        apiCalling()
    }

    func apiCalling(){
        if let url = URL(string: "https://pincood.com/pincood/public/api/user/trips") {
            var request = URLRequest(url: url)
            request.allHTTPHeaderFields = [
                "Content-Type": "application/json",
                "Session": "fb4e7f9b-0f31-4709-",
                "AUthorization":"<some key>"
            ]
            
            URLSession.shared.dataTask(with: request) { (data, response, error) in
                guard error == nil else { return }
                guard let data = data else { return }
                do{
                    let codabledata = try JSONDecoder().decode([PastRide].self, from: data)
                    print(codabledata)
                    DispatchQueue.main.async {
                        self.past = codabledata
                        self.mTable.reloadData()
                    }
                } catch {
                    print(error)
                }
            }.resume()
        }
    }

In the extension we try:

extension PastTripsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return past.count
        print(past.count)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PastTableView
        cell.usernm.text = past[indexPath.row].provider.firstName
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let details : PastDetailView = self.storyboard?.instantiateViewController(withIdentifier: "PastDetailView") as! PastDetailView
        navigationController?.pushViewController(details, animated: true)
        
    }
}

Upvotes: 0

Views: 358

Answers (1)

Ayush S Bhatt
Ayush S Bhatt

Reputation: 1

You need to set table view's delegate and datasource properties in viewDidLoad. Update your viewDidLoad to look like this:

override func viewDidLoad() {
    super.viewDidLoad()
    let nibCell = UINib(nibName: "PastTableView", bundle: nil)
    mTable.register(nibCell, forCellReuseIdentifier: "cell")
    mTable.delegate = self
    mTable.datasource = self
    apiCalling()
}

Upvotes: 0

Related Questions