I made a SearchViewController with tableView. I put some data in tableView from server (pictures of cats). But now I want to show not only all pictures, but also filtered by certain categories images. For this I suppose I need to push my second array with category's images into the tableView. I guess that to achieve this goal I need to reload tableView and change its dataSource, but how to realize it correctly I don't understand.
Here is the method to get all pictures of cats
func fetchData() { guard let endPoint = // myEndpoint else { return } endpoint.queryItems = queryParameters.map({ (key, value) in URLQueryItem(name: key, value: value) // some parameters }) guard let url = endpoint.url else { return } var request = URLRequest(url: url) request.setValue(ApiClient.Identifiers.apiKey, forHTTPHeaderField: "x-api-key") let task = URLSession.shared.dataTask(with: request) { data, response, error in DispatchQueue.main.async { if error != nil { print(error.debugDescription) } else { do { let myData = try JSONDecoder().decode([CatModel].self, from: data!) self.catsModel = myData // catsModel is an array with struct with cats info (breed, category, id, etc.) self.tableView.dataSource = myData as? any UITableViewDataSource self.tableView.reloadData() } catch let error { print(error) } } } } task.resume()
}
Here is the method for filter by categories id :
func fetchCategoryData(categoryID: Int) { let endpoint = URLComponents // url components guard let url = endpoint?.url else { return } var request = URLRequest(url: url) request.setValue(ApiClient.Identifiers.apiKey, forHTTPHeaderField: "x-api-key") let task = URLSession.shared.dataTask(with: request) { data, response, error in DispatchQueue.main.async { if error != nil { print(error.debugDescription) } else { do { let myData = try JSONDecoder().decode([CatModel].self, from: data!) self.catsModel = myData self.tableView.reloadData() } catch let error { print(error) } } } } task.resume() }In CategoryViewController I made this method:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let searchViewController = SearchViewController() let cat = catsModel[indexPath.row] searchViewController.fetchCategoryData(categoryID: cat.id) // this line works, but in fetchCategoryData doesn't happenings the reload of tableView with new data}
Thank you very much!
