0

I'm trying to change text on label when app will enter foreground but I always get

fatal error: unexpectedly found nil while unwrapping an Optional value

ViewController.swift

  @IBOutlet var textLabel: UILabel!

    func showLabel() {
        textLabel.text = "Welcome back"
    }

and

AppDelegate.swift

func applicationWillEnterForeground(application: UIApplication) {
       ViewController().showLabel()
    }

Any Idea how to fix it?

chrisco
  • 147
  • 2
  • 10
  • Has that view controllers view been loaded? – Wain Jan 19 '15 at 19:56
  • possible duplicate of [Nil when unwrapping an Optional Value in didBecomeActive()](http://stackoverflow.com/questions/28016699/nil-when-unwrapping-an-optional-value-in-didbecomeactive) – David Berry Jan 19 '15 at 20:48
  • yep this was my solution: http://stackoverflow.com/questions/28016699/nil-when-unwrapping-an-optional-value-in-didbecomeactive but I Couldn't find it before. It was asked today – chrisco Jan 19 '15 at 20:54

3 Answers3

2

thanks for answers! I managed it with

NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLabel", name: UIApplicationDidBecomeActiveNotification, object: nil)

in viewDidLoad

and then in AppDelegate

func showLabel() {}

based on : Nil when unwrapping an Optional Value in didBecomeActive()

Community
  • 1
  • 1
chrisco
  • 147
  • 2
  • 10
1

As I explained in a previous post, you should initialize your label in the viewDidLoad function of your view controller.

In fact, at the time you are in applicationWillEnterForeground, your view controller has not been yet initialized, so the label textLabel is null (nil) and you are trying to access a property of a null object (reason of your error).

ViewController.swift:

@IBOutlet var textLabel: UILabel!

func viewDidLoad() {
    textLabel.text = "Welcome back"
}
Community
  • 1
  • 1
Jérôme
  • 8,016
  • 4
  • 29
  • 35
1

The issue is, you are creating a new instance of your ViewController and trying to set the data to it.

Instead of that use the existing one ( You created on didFinishLaunchingWithOptions: )

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • I know that but how can I get access to the existing one? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } – chrisco Jan 19 '15 at 20:34
  • @chrisco: If you are setting the ViewController from storyboard then, try the reverse mechanism (means from view control fetch the data from app delegate). Else set your ViewController as the rootViewController property of your application – Midhun MP Jan 19 '15 at 20:44