Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Update a value in RootViewController from AppDelegate when the app comes to background state

I have a simple view application with one main view only.

I'm trying to show updated time value in a label inside a view when the app comes to background state.

The scenario is:

1 - Single View Application project

2 - Only one View (ViewController) with one Label to show the date

3 - In the AppDelegate:applicationWillEnterForeground get the current time

func applicationWillEnterForegound(application: UIAPplication){
    var date:String = GetDate()
    --> update View Label with date here
}

4 - Show the current time on ViewController

I'm trying with delegates, but the problem is that the view was the last visible element in the app and methods as viewDidLoad, viewWillAppear are called once.

like image 234
amelian Avatar asked Jul 26 '16 13:07

amelian


2 Answers

As others have noted, you can use the Notification framework to do this from within your view controller so your appDelegate does not need to reference your view controller. Add a line like this in your controller:

NSNotificationCenter.defaultCenter().addObserver(self,
    selector: #selector(appWillEnterForeground), 
    name: NSNotification.Name.UIApplicationWillEnterForeground,
    object: nil 

In Swift 3 the syntax changes slightly:

NotificationCenter.default.addObserver(self, 
    selector: #selector(appWillEnterForeground),
    name: NSNotification.Name.UIApplicationWillEnterForeground,
    object: nil)

In Swift 4.2 the syntax changes again:

NotificationCenter.default.addObserver(self, 
    selector: #selector(appWillEnterForeground), 
    name: UIApplication.willEnterForegroundNotification, 
    object: nil)

then define the function you name in the selector:

@objc func appWillEnterForeground() {
   //...
}
like image 146
Matt Weinecke Avatar answered Oct 14 '22 08:10

Matt Weinecke


You can listen for the UIApplicationWillEnterForegroundNotification inside your ViewController. If you know its views are visible, it can find the date and change its own label.

like image 1
Phillip Mills Avatar answered Oct 14 '22 10:10

Phillip Mills