amelian amelian - 1 year ago 162
Swift Question

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.

Answer Source

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:

    selector: #selector(appWillEnterForeground), 
    name: NSNotification.Name.UIApplicationWillEnterForeground,
    object: nil 

In Swift 3 the syntax changes slightly:

    selector: #selector(appWillEnterForeground),
    name: NSNotification.Name.UIApplicationWillEnterForeground,
    object: nil)

then define the function you name in the selector:

func appWillEnterForeground() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download