How to reload tableview from another view controller in swift

When I dismiss a modal view controller I want the tableview to update, I am using the form sheet presentation style on iPad so the viewWillAppear and the viewDidAppear methods will not work


Solution 1:

You can do this:

In your tableView Controller:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
}
 
@objc func loadList(notification: NSNotification){
    //load data here
    self.tableView.reloadData()
}

Then in the other ViewController :

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)

Solution 2:

Swift 3 version code: In your first view controller:

override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
    }

func loadList(){
        //load data here
        self.tableView.reloadData()
    }

In your second view controller:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)

Solution 3:

I find the segue approach more elegant.

Let's say that we have ViewControllerA and a ViewControllerB. We are at ViewControllerB and we want from ViewControllerB to jump straight back to ViewControllerA and update the table view in ViewControllerA.

In ViewControllerA add the following action in your ViewController class:

@IBAction func unwindToViewControllerA(segue: UIStoryboardSegue) {
    DispatchQueue.global(qos: .userInitiated).async {
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

Yes, this code goes in the ViewController of the ViewController you want to go back to!

Now, you need to create an exit segue from the ViewControllerB's storyboard (StoryboardB). Go ahead and open StoryboardB and select the storyboard. Hold CTRL down and drag to exit as follows:

enter image description here

You will be given a list of segues to choose from including the one we just created:

enter image description here

You should now have a segue, click on it:

enter image description here

Go in the inspector and set a unique id: enter image description here

In the ViewControllerB at the point where you want to dismiss and return back to ViewControllerA, do the following (with the id we set in the inspector previously):

self.performSegue(withIdentifier: "yourIdHere", sender: self)

Now, whenever you use the segue to return back to ViewControllerA, the ViewControllerA will update the TableView straightaway.