I am new in the async/await in swift and I am trying to assign the job global variable in MyViewController a value using an async function which is then called in the ViewWillAppear.
Inside the async function, I get a value for job but when I try to pass that to a cell property in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell I get nil.
Can anyone know why this is happening and how to solve it?
class MyViewController: UIViewController {
private var job: Job!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Task { [weak self] in
await self?.getJob()
}
}
private func getJob() async {
job = await viewModel.getJob(byID: "xxxxxxx") // will return a Job Object
// more code...
print(job) // it's ok
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(job) // it is nil!!!
}
}
In this scenario, tableView loads before job data fetch. So you should add tableView.reloadData() after fetch the job data to reload the tableView with new fetched data.