Сначала создайте свой протокол следующим образом:
protocol CountryViewControllerDelegate: class {
func updateLabels(_ controller: CountryViewController, country: String, allCases: Int, recovered: Int, deaths: Int)
}
Затем в вашем CountryViewController:
class CountryViewController: UIViewController {
weak var delegate: CountryViewControllerDelegate?
// code ...
}
extension CountryViewController: CountryViewControllerDelegate {
func updateLabels(_ controller: CountryViewController, country: String, allCases: Int, recovered: Int, deaths: Int) {
print("CountryViewController:", #function)
DispatchQueue.main.async {
// update your labels in the main thread
// self.deathLabel.text = String(deaths)
// self.recoveredLabel.text = String(recovered)
// self.infectedLabel.text = String(allCases)
print("Country:", country)
print("deaths:", deaths)
print("recovered:", recovered)
print("infected:", allCases)
}
}
}
Наконец, в вашем CountryTableViewController:
class CountryTableViewController: UITableViewController, CountryViewControllerDelegate {
weak var delegate: CountryViewControllerDelegate?
// code ...
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Select Your Country"
delegate = self
}
// code ...
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let country = countries[indexPath.row]
let string = "https://corona.lmao.ninja/countries/\(country.lowercased())"
guard let url = URL(string: link) else { return }
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyBoard.instantiateViewController(withIdentifier: "CountryViewController") as! CountryViewController
controller.delegate = self
controller.modalPresentationStyle = .pageSheet
controller.title = country
let countryNavigationController = UINavigationController(rootViewController: controller)
countryNavigationController.viewControllers = [controller]
self.present(countryNavigationController, animated: true)
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
if let string = String(data: data, encoding: .utf8), string == "Country not found" {
self.updateLabels(controller, country: country, allCases: 0, recovered: 0, deaths: 0)
return
}
do {
let allCases = try JSONDecoder().decode(CountryCases.self, from: data)
self.updateLabels(controller, country: country, allCases: allCases.cases, recovered: allCases.recovered, deaths: allCases.deaths)
} catch {
print("JSON error:", error)
}
}.resume()
}
func updateLabels(_ controller: CountryViewController, country: String, allCases: Int, recovered: Int, deaths: Int) {
print("CountryTableViewController:", #function)
controller.updateLabels(controller, country: country, allCases: allCases, recovered: recovered, deaths: deaths)
}
}
![enter image description here](https://i.stack.imgur.com/K9PHl.jpg)
Образец проекта