Search code examples
swiftuitableviewalamofireswift5

How to fill-in an UItableview after extracting data with a function?


I have troubles while filling-in the cells of my table view :

I would like to fill-in the cells once the function Fetch() finished runned, then the arrayComponents is filled by the informations I would like to display in my cells :

var arrayComponents:Array<String> = Array(repeating: "", count: 4)

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let  cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)

    cell.textLabel!.text = arrayComponents[indexPath.row]

    cell.imageView!.image = image

    return cell
}

func fetch(jan: String){

                    self.fetchAll { result in
                        switch result {
                        case .failure(let error):
                            print(error)

                        case .success(let values):
                            self.arrayData = values

                            self.arrayComponents = ["\(self.arrayData[1])","\(self.arrayData[2])","\(self.arrayData[3])","\(self.arrayData[4])"]

                        }
                    }
                }

        case .failure(let error):
            print("\(error) in fetch")
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    fetch(jan: dataFromFirst)

    tableView.dataSource = self
    tableView.delegate = self

}

}

How can I load the table view once the fetch() finished and returned the values ?


Solution

  • Reload your tableView data after fetching

       func fetch(jan: String){
    
            self.fetchAll { result in
            switch result {
            case .failure(let error):
                  print(error)
    
            case .success(let values):
                 self.arrayData = values
                 self.arrayComponents = ["\(self.arrayData[1])","\(self.arrayData[2])","\(self.arrayData[3])","\(self.arrayData[4])"]
    
                        }
                    }
           //Reload data
    
           tableView.reloadData()
    
            }