我正在尝试在UITableViewCell
内填充自定义UITableView
,但没有将数据加载到单元格中。我已经创建了一个配方数组,并使用API调用中的数据填充了该数组。调试代码后,似乎数组计数为0,因此尽管我正在调用getRecipes()
方法来填充数组,但未将数据加载到单元格中。关于这是什么原因或如何解决的任何想法? ?
下面是我的代码:
class MainPageViewController: UIViewController
{
//declare variables
@IBOutlet weak var recipeTableView: UITableView!
var recipes: [Recipe] = []
override func viewDidLoad()
{
recipeTableView.delegate = self
recipeTableView.dataSource = self
self.recipeTableView.reloadData()
recipes = self.getRecipes()
print("array: \(recipes.count)")
super.viewDidLoad()
}
}
//ui table view functions
extension MainPageViewController: UITableViewDataSource, UITableViewDelegate
{
//set the number of items in the table view to the array of objects
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
print("array count: \(recipes.count)")
return recipes.count
}
override func viewDidAppear(_ animated: Bool) {
recipeTableView.reloadData()
super.viewDidAppear(animated)
}
//fetch the data in the array and set it in the table view cells
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
print("code here")
let recipe = self.recipes[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeCell")
as! UIRecipeCell
print("code here")
cell.setRecipe(recipe: recipe)
return cell;
}
func getRecipes() -> [Recipe]
{
var recipesTemp: [Recipe] = []
// Hit Spoonacular endpoint using Moya as the middleman
let provider = MoyaProvider<SpoonacularAPI>()
provider.request(.getRecipes(limitLicense: true, number: 10, tags: "vegetarian, dessert"))
{
switch $0
{
case .success(let response):
do {
// Only allow successful HTTP codes
_ = try response.filterSuccessfulStatusCodes()
// Parse data as JSON
let json = try JSON(data: response.data)
print("json log: \(json)")
// Parse each recipe's JSON
recipesTemp = json["recipes"].arrayValue.map({ Recipe(json: $0) })
print("array count: \(recipesTemp.count)")
print("array : \(recipesTemp)")
}
catch {
print(error.localizedDescription)
}
case .failure(let error):
print(error.localizedDescription)
}
self.recipeTableView.reloadData()
}
return recipesTemp
recipeTableView.reloadData()
}
}
答案 0 :(得分:2)
您获取食谱的API异步进行。
您不能从包含异步任务的方法中返回任何内容。
viewDidLoad
中仅调用方法。getRecipes
中删除返回值,这毫无意义。或者使用完成处理程序。
override func viewDidLoad()
{
recipeTableView.delegate = self
recipeTableView.dataSource = self
getRecipes()
}
func getRecipes()
{
// Hit Spoonacular endpoint using Moya as the middleman
let provider = MoyaProvider<SpoonacularAPI>()
provider.request(.getRecipes(limitLicense: true, number: 10, tags: "vegetarian, dessert"))
{
switch $0
{
case .success(let response):
do {
// Only allow successful HTTP codes
_ = try response.filterSuccessfulStatusCodes()
// Parse data as JSON
let json = try JSON(data: response.data)
print("json log: \(json)")
// Parse each recipe's JSON
self.recipes = json["recipes"].arrayValue.map({ Recipe(json: $0) })
print("array count: \(recipesTemp.count)")
print("array : \(recipesTemp)")
DispatchQueue.main.async {
self.recipeTableView.reloadData()
}
}
catch {
print(error.localizedDescription)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
请注意,在recipes
末尾,您不能不能对viewDidLoad
进行操作。
答案 1 :(得分:0)
这里的问题是您的请求函数在实际请求到达响应之前返回结果
您应该改为使用完成处理程序修改逻辑
func getRecipes(complition: @escaping ((_ response: [Recipe]) -> ())) {
// Your request logic
// onSuccess return the array like this
// complition(resultArray)
}