I have 2 Controllers: CollectionViewController
and DetailViewController
. In CollectionViewController
I fetched Data and get coctails
. Now I want get coctails?.drinks?[indexPath.row]
and pass in DetailViewController
, where I need to fetchRequest again but with another API and new url. But when loading DetailViewController
, the method networkDataService.fetchDrink(drinkName: drinkName)
does not work.
What I did wrong?
struct Coctail: Codable {
let drinks: [Drink]?
}
struct Drink: Codable {
let strDrink : String?
let strDrinkThumb : URL?
}
class NetworkDataService {
let networkManager = NetworkManager.shared
func fetchCoctails(completion: @escaping (Coctail?) -> Void) {
let url = "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail"
networkManager.fetchData(url: url, completion: completion)
}
func fetchDrink(drinkName: String, completion: @escaping (Coctail?) -> Void) {
let url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=\(drinkName)"
networkManager.fetchData(url: url, completion: completion)
}
}
class CollectionViewController: UICollectionViewController {
var coctails: Coctail?
let networkDataService = NetworkDataService()
override func viewDidLoad() {
super.viewDidLoad()
networkDataService.fetchCoctails() { (coctails) in
self.coctails = coctails
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return coctails?.drinks?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let drink = coctails?.drinks?[indexPath.row]
cell.config(drink: drink)
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let indexPath = collectionView.indexPathsForSelectedItems?.first else { return }
let drink = coctails?.drinks?[indexPath.row]
let destination = segue.destination as! DetailViewController
destination.drinkName = drink?.strDrink ?? ""
}
}
class DetailViewController: UIViewController {
var drinkName = ""
var coctail: Coctail?
let networkDataService = NetworkDataService()
override func viewDidLoad() {
super.viewDidLoad()
networkDataService.fetchDrink(drinkName: drinkName) { (coctail) in
self.coctail = coctail
}
}