Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-load ViewController when app is resumed

My app only has one ViewController and thus one ViewController.swift

I'd like for that ViewController to be re-loaded whenever the user resumes the app (multitasking). There is initialisation code in the viewDidLoad() function that does not fire when the app is resumed. I want this code to fire whenever the app is resumed and thus I would like to re-load the ViewController when the app is resumed.

Is there an elegant way to do this in Swift?

Thank you.

like image 277
Spencer Avatar asked Oct 31 '22 19:10

Spencer


1 Answers

You can add and observer to your view controller to notify when your app enters foreground. Whenever your app enters foreground, this method reloadView will be called by the observer. Note that you will have to call this method yourself self.reloadView() when the view loads for the first time.

Here is the Swift code for this:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.reloadView()

    NSNotificationCenter.defaultCenter().addObserver(self,
     selector: "reloadView",
     name: UIApplication.willEnterForegroundNotification,
     object: nil)
}

func reloadView() {
    //do your initalisations here
}
like image 129
Nishant Avatar answered Nov 15 '22 05:11

Nishant