0

Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data 
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.

  • Welcome to stack overflow. Please [take the tour](https://stackoverflow.com/tour). – Xcoder Dec 04 '17 at 16:23
  • It seems to me that you don't need to load the view controller before the segue, you just need to load the data before the segue. Load the data in the main controller, then pass the data to the table controller in prepareForSegue. Set the data in a member var of the table controller and use that var for all the table view delegate methods. – FryAnEgg Dec 04 '17 at 16:43
  • A better approach would be to keep the loading in the table view controller but call it on prepare for segue – zombie Dec 04 '17 at 16:44

3 Answers3

0

Try putting the API call in the ViewDidAppear Method of the Table View Controller Class. That way the app will segue to the View Controller then call the data. The app will appear faster but take the same amount of time. This way you can also manage timeouts and default data for the ViewDidLoad.

Rody Davis
  • 1,825
  • 13
  • 20
0

Thank you all for your help!

I actually incorporated FryAnEgg's comment and created a Global Variable in my Main VC to load in the API.

Main VC:

var Global X  

class Main VC: UIViewController {
   loadDataFunc(){
      GlobalX.append(data)
     }
 }

TableView:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return GlobalX.count //calling Global Variable
  }
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  return cell
  }

I then called the Global Variable in the Table View Controller and it worked !

Thanks again everyone

0

To load tablview in main view before segueing you can use NSNotificationCenter. It is call in ViewDidLoad so it will reload data.

Dhaval Solanki
  • 71
  • 1
  • 2
  • 9