Search code examples
iosiphoneswiftuilabelviewdidload

Swift UILabel is nil (error) when app goes in background


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?


Solution

  • 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 viewDidLoad add the following

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("enteringForeground:"),
      name: UIApplicationWillEnterForegroundNotification, object: nil)
    

    The add a function to your ViewController

    func enteringForeground(notification: NSNotification) {
       // Whatever you need to do to refresh UI
       // DO NOT CALL viewDidLoad
    }
    
    deinit {
    
       NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }