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.
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() {
//...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With