John511 John511 - 6 months ago 19
Swift Question

swift how to get self.tableView.reloadTable() when UITableViewController is not class type

I have a normal view controller with a table view inside, so the class is just a normal UIViewController, therefor I am unable to call self.tableView with this. I have an asynchronous call to create an array of Aircraft objects that is taken from an online database, but that is only completed after the table cells are initially loaded. I am trying to update the table cells after this asynchronous call is completed, but am unsure how to do so. I do the asynch call in viewDidLaod(). Here is my current code that only displays the loading tags since the update has not taken place for the aircraft array.

class AircraftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let log = Logger( id: String(AircraftViewController.self) )
let dvc = DownloadViewController()
var aircraftArr = [Aircraft]()

override func viewDidLoad() {
super.viewDidLoad()

dvc.getMobileSystemOverviewHTML {
dispatch_async(dispatch_get_main_queue()){
self.aircraftArr = self.dvc.aircraft
self.log.debug("\n\n\n\n\n \(self.aircraftArr) \n\n\n\n\n")
}
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table View Delegate Methods

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AircraftCell", forIndexPath: indexPath) as! AircraftCell


if indexPath.row < aircraftArr.count{
let singleAircraft = aircraftArr[indexPath.row] as Aircraft
cell.aircraft = singleAircraft
} else {
cell.aircraft = Aircraft(tailID: "Loading", aircraftSN: "Loading", Box_SN: "Loading")
}

return cell
}

Answer

You need to create the outlet of tableview like this

@IBOutlet var tableView: UITableView!

After that reload this tableview in your dispatch_async

dvc.getMobileSystemOverviewHTML {
    dispatch_async(dispatch_get_main_queue()){
        self.aircraftArr = self.dvc.aircraft
        self.tableView.reloadData()
        self.log.debug("\n\n\n\n\n \(self.aircraftArr) \n\n\n\n\n")
    }
}

Hope this will help.