0

I have a category collectionView on which there are category labels on each cell when I click any cell the label Value gets passed to second viewController's category variable using prepareForSegue and when the value of category variable gets set the didSet calls loadData() function.

func loadData()
{

    let companyData = Database.database().reference().child("CompanyReviews")
    companyData.queryOrdered(byChild: "Category").queryEqual(toValue: category).observe(.value, with: {(snapshot) in
        for child in snapshot.children
        {
            let companyObject = Companies()
            let dataSnapshot = child as! DataSnapshot

            companyObject.companyName = dataSnapshot.childSnapshot(forPath: "CompanyName").value as! String
            companyObject.owner = dataSnapshot.childSnapshot(forPath: "CompanyOwner").value as! String
            companyObject.contactNumber = dataSnapshot.childSnapshot(forPath: "ContactNumber").value as! String
            companyObject.location = dataSnapshot.childSnapshot(forPath: "location").value as! String
            companyObject.gstNumber = dataSnapshot.childSnapshot(forPath: "GSTNumber").value as! String
                self.companyArray.append(companyObject)
            }
            if self.companyArray.count > 0
            {
                self.CompanyTable.reloadData()
                print(self.companyArray.count)
            }
            else
            {
                self.noData.text = "No Data Available"
                self.CompanyTable.backgroundView = self.noData
            }
        })
}

If there exists some data under that category the tableView loads that data if not then tableViews backgroundView shows 'No Data Available'. The app runs perfectly. Now there is one category that has no data under it and two categories with data. The problem is that after selecting a category and then coming back and selecting other category the app crashes at self.CompanyTable.reloadData() with error:

Unexpectedly found nil while unwrapping the optional.

I really don't know why is this happening, I searched on google and even went through some answers on stackOverflow but no clues.I am a beginner in swift programming so please help me on this issue.

Amit
  • 4,837
  • 5
  • 31
  • 46

1 Answers1

0

when the value of category variable gets set the didSet calls loadData()

get rid off didSet it's the reason for the crash , you need to call loadData() in viewDidLoad , the reason is that all outlets of the VC are nil until the VC loads which not true when control is inside the prepareForSegue , you may be lucky if network speed is not fast , but you should not leave your app under possibilities

Also replace observe with observeSingleEvent as the former is observer that's called every change in server

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87