gpt4 book ai didi

ios - 将 Json 响应从一个 Viewcontroller 传递到另一个 Viewcontroller 并填充 CollectionView

转载 作者:行者123 更新时间:2023-11-29 05:34:35 25 4
gpt4 key购买 nike

我正在尝试将 Http 请求的 Json 响应从一个 Controller 传递到另一个 Controller ,在第二个 Controller 中我想根据收到的数据创建一个 Collection View 。


import UIKit

class TableViewController: UITableViewController {

let ingredientList = Ingredients().Ingredients
public var arrayDrinks: Array<Any> = []
let session = URLSession.shared


override func viewDidLoad() {
super.viewDidLoad()

self.tableView.reloadData()
tableView.dataSource = self
tableView.delegate = self

}

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

// MARK: - number of rows
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ingredientList.count
}

// MARK: - creating cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellaIng", for: indexPath)

let singoloIngrediente = self.ingredientList[indexPath.row]

cell.textLabel?.text = singoloIngrediente
return cell
}


// MARK: - get the Selected Item
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let selectedItem: String = ingredientList[indexPath.row]
print("The selected ingredient is: \(selectedItem)")

// parameter for http request
let param = String(selectedItem.replacingOccurrences(of: " ", with: "_"))

let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=\(param)")!

// MARK: - Http request

let task = session.dataTask(with: url) { data, response, error in

if error != nil || data == nil {
print("Client error!")
return
}

guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print("Server error!")
return
}

do {
// data from network request
let decoder = JSONDecoder()
let response = try decoder.decode(ObjectDrink.self, from: data!) // ObjectDrink from Model

self.arrayDrinks.append(response.drinks)
let destinationVC = DrinksListCollectionViewController()
destinationVC.remoteArray = response.drinks
print("print array drink \(destinationVC.remoteArray)")

} catch { print(error) }

}
performSegue(withIdentifier: "InglistSegue", sender: self)
task.resume()

// let destinationVC = DrinksListCollectionViewController()
// destinationVC.remoteArray = self.arrayDrinks
// destinationVC.performSegue(withIdentifier: "InglistSegue", sender: self)

} // END didSelectRowAt

}

当我将响应打印到控制台时,第二个 Controller 的数组为空,因此没有数据从第一个响应(数组)传递到另一个 Controller

最佳答案

您需要将其呈现在 URLSession.shared.dataTask 的回调中,例如

DispatchQueue.main.async {
self.arrayDrinks.append(response.drinks)
let destinationVC = DrinksListCollectionViewController()
destinationVC.remoteArray = response.drinks
print("print array drink \(destinationVC.remoteArray)")
self.present(destinationVC,animated:true,completion:nil)
}

如果是一个segue,则将上面替换为(也在完成内)

DispatchQueue.main.async {
performSegue(withIdentifier: "InglistSegue", sender: response.drinks)
}

添加此方法

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! DrinksListCollectionViewController
destinationVC.remoteArray = sender as! [Model] // model it type of drinks
}

关于ios - 将 Json 响应从一个 Viewcontroller 传递到另一个 Viewcontroller 并填充 CollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57167285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com