'Data not updated in TableView after searchBarSearchButtonClicked
I have the following code to search a database for recipes then return that data to my View Controller:
var discoveredRecipe: RecipeDiscovered? = nil
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
var searchText = searchBar.searchTextField.text
self.searchTask?.cancel()
if searchText != "" {
discoverModel.discoverRecipes(searchText: searchText ?? "") {
self.searchTextActive = true
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
searchBar.showsCancelButton = true
}
I can confirm that the data is returned to my View Controller and assigned to discoveredRecipe in the above
I then have the following to display that returned data in my Table View:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("DiscoveredRecipe:\(discoveredRecipe)")
let cell = tableView.dequeueReusableCell(withIdentifier: "MealPlanCell", for: indexPath) as! MealPlanCell
// If searchText entered
if searchTextActive == true {
print("DiscoveredRecipe:\(discoveredRecipe)")
cell.displayRecipeShort(recipeTitle: (discoveredRecipe?.hits![indexPath.row].recipe.label)!, recipeSourceUrl: (discoveredRecipe?.hits![indexPath.row].recipe.url)!, recipeImage: (discoveredRecipe?.hits![indexPath.row].recipe.image)!, indexPathRow: indexPath.row)
}
return cell
}
It doesn't matter where I put print("DiscoveredRecipe:\(discoveredRecipe)") within func tableView, it keeps printing as nil. What am I missing to get the newly assigned discoveredVariable within the func tableView scope?
Solution 1:[1]
Please check whether your delegate method which is updating the discoveredRecipe is called or not. if it is not called that's mean delegation is not setup properly. That might be the problem discoveredRecipe value is nil.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | abhishek kumar thakur |
