I am trying to get an API call to populate the cells of a list view but cannot seem to get the data to be gathered before the cells are generated. I have tried making a completion handler as like here to no avail as well as a semaphore from the same link. While the completion handler compiled, it still did not get the data in time when executing (admittedly it was my first attempt at a completion handler). Here is the original code w/o the completion handler:
override func viewDidLoad() {
super.viewDidLoad()
RestaurantListView.delegate = self
RestaurantListView.dataSource = self
//API setup
guard let url = URL(string: "https://myURL.com") else {
print("ERROR: Invalid URL")
return
}
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) -> Void in
// URL request is complete
guard let data = data else {
print("ERROR: Unable to access content")
return
}
guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
print("Error: Couldn't decode data into Blog")
return
}
self.myData = blog
}
task.resume()
}
The table and cells are initialized below these functions:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = RestaurantListView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = myAPIValue
return cell!
}
I have several print statements to track the program and it goes through viewDidLoad then the first tableView which sets up the table then the second which handles the cells, finally it goes through the URL task.
I have rewritten this dozens of different ways and have no idea how to make this execute in the correct order.