Search code examples
iosswifttableview

How to pass API data to table view cells


I'm having some trouble passing my API returned data to table view cells. I am appending the data to an array and then passing this array to the table view (as usual) to get the number of rows and data for the cells. When I print inside the function where I am appending, the titles are shown in the array. Outside they're not. Any idea? Relevant code below:

import UIKit

class ProductTableViewController: UITableViewController, UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!
        
    @IBOutlet var tabView: UITableView!
    var filteredData = ["Title1"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getProducts { (products) in
            for product in products {
                self.filteredData.append(product.title)
            }
        }

    }
        
        func getProducts(completionHandler: @escaping([ProductDetail]) -> Void) {
            let url = URL(string: "exampleAPIURL")!

            let dataTask = URLSession.shared.dataTask(with: url) {data, _, _ in
                guard let jsonData = data else { return }
                do {
                    let decoder = JSONDecoder()
                    let productsResponse = try decoder.decode(Products.self, from: jsonData)
                    let productDetails = productsResponse.data
                    for name in productDetails {
                        self.filteredData.append(name.title)
                    }
                    completionHandler(productDetails)
                }catch {
                    print(error.localizedDescription)
                }
            }
            dataTask.resume()
        }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if filteredData == nil {
            return 1 }
        else {
        return filteredData.count
        }

    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
        UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
            for name in filteredData {
                if name != nil {
                    let product = filteredData[indexPath.row]
                    cell.textLabel?.text = product

                } else {
                    cell.textLabel?.text = "name"

                }
            }

            return cell
    }

I am only receiving the hardcoded strings in the filteredData array when I run the simulator. Is there a different way to pass the JSON?


Solution

  • Reload the table view after the data is collected:

    getProducts { (products) in
        for product in products {
            self.filteredData.append(product.title)
        }
        self.tabView.reloadData()
    }