i want to get data from firebase firestore and put that into a tableview in a new view
but when tableview is getting data it’s nil and i got unwrapping error like this picturescreenshot of unwrapping error
this is my tableview code :
class ParcelViewController:UIViewController, UITableViewDataSource, UITableViewDelegate {
let tableCell = ParcelTableViewCell()
var parcelDataModel = MainViewModel()
@IBOutlet weak var parcelTable: UITableView!
override func viewDidLoad() {
self.parcelDataModel.vc = self
view.backgroundColor = .white
parcelDataModel.getCollectionData()
print("Hi")
}
var selectionDelegate : ParcelSelectionDelegate!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if parcelDataModel.parcels.count > 0 {
return self.parcelDataModel.parcels.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = parcelTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ParcelTableViewCell
let current = self.parcelDataModel.parcels[indexPath.row]
cell.parcelTitleLabel.text = current.parcel_type
cell.parcelImage.image = UIImage(named: current.parcel_img_url)
cell.parcelWeightlabel.text = "(current.parcel_min_weight) - (current.parcel_max_weight)"
cell.parcelDescriptionLabel.text = current.parcel_description
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selected = self.parcelDataModel.parcels[indexPath.row]
selectionDelegate.parcelDidSelect(parcelType: selected.parcel_type)
}
}
and i want to this code self.parcelDataModel.vc = self
comes before viewdidload
i’ve tried it in loadView but it didn’t worked.
2
Answers
i just had to change my if statement in numberOfRowsInSection like below
and it works now.
As mentioned in the comments, aiming for an earlier lifecycle access point than
viewDidLoad()
isn’t likely to help in this situation: it’s almost certain that the view controller lifecycle will complete before a Firebase request will be returned.Considering that, modification to the view controller load UX is the answer. There are two main approaches here:
Option 1 might look like:
Option 2 might look like:
Then: