I am trying to fetch data from Parse and populate a table view controller. I have the following defined in the VC:
class OrdersViewController: UITableViewController{
/*************************Global Objects************************/
var userObject = UserClass()
var utilities = Utilities()
var orderObject = OrderClass()
var objectsArray:[PFObject]!
/*************************UI Components************************/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
SwiftSpinner.show("Please Wait...Populating Table")
let query = PFQuery(className:"Orders")
query.whereKey("appUsername", equalTo:PFUser.currentUser()!["appUsername"])
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
SwiftSpinner.hide()
self.objectsArray = objects
} else {
SwiftSpinner.hide()
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
SwiftSpinner.hide()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! OrderCell
let row = indexPath.row
cell.orderRetailerName.text = objectsArray[row]["nameRetailer"] as? String
cell.status.text = objectsArray[row]["status"] as? String
cell.dueDate.text = objectsArray[row]["dueDate"] as? String
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
/*tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print("")*/
}
}
in the viewWillAppear I am trying to fetch the data from the Parse backend and populate the table with it. When I run the program, I am getting the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
the error is caused by objectsArray.count line in numberOfRowsInSection. Fair enough...It is trying to get the count but clearly the array is empty because the job of fetching data is running in background and isn't completed yet. This is what I need help with. Am I placing the fetching code in the right location (i.e. viewWillAppear)? If not, where should I put it instead to ensure it executes before the table actually attempts loading.
Thanks,