I have some code that changes the text of a UILabel, it works fine when the app is run first time around but when I close it (app goes to background) and then I reopen it, the UILabel is nil and the text can't be set again.
The text is set to the UILabel in viewDidLoad() function and I call viewDidLoad() in applicationWillEnterForeground function to set the text to the UILabel again - that's when it crashes giving the error fatal error: unexpectedly found nil while unwrapping an Optional value. I debugged it and the nil found is the UILabel
Here is some of the code in AppDelegate.swift:
func applicationWillEnterForeground(application: UIApplication) {
ViewController().refresh()
}
And in ViewController.swift:
func refresh() {
self.viewDidLoad()
}
Do you have any ideas why the UILabel becomes nil when the app goes to background?
Rather than trying to hold a reference to your view controller from your app delegate, it is better to simply have your view controller subscribe to the foreground entry event -
In your
viewDidLoadadd the followingThe add a function to your ViewController