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

时间:2019-07-23 15:13:18

标签: ios swift

我正在尝试将Http请求的Json响应从一个控制器传递到另一个控制器,在第二个控制器中,我想根据接收到的数据创建一个集合视图。


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

}

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

2 个答案:

答案 0 :(得分:0)

您要移动的视图控制器尚不可用,并且您的行:

let destinationVC = DrinksListCollectionViewController()

创建一个新的视图控制器,它不是您的应用过渡到的控制器。要使用将显示的视图控制器,请像下面这样使用prepare(for segue: UIStoryboardSegue, sender: Any?)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? DrinksListCollectionViewController {
        destinationVC.remoteArray = self.arrayDrinks
    }
}

答案 1 :(得分:0)

您需要将其呈现在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 
}