-1

Im getting this error:

fatal error: unexpectedly found nil while unwrapping an Optional

...when i try to change a labels Text in the Interface controller, calling the function from the notification controller, when receiving a notification. Thats my code:

InterfaceController.swift

func test() {
    patt.setText("testtesttest")
}

NotificationController.swift

let controller = InterfaceController()
override func didReceiveRemoteNotification(remoteNotification: [NSObject : AnyObject], withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) {
    controller.test()
    completionHandler(.Custom)
}

The error disappears when i remove the function and print works fine so why doesn't setText work? How can it be nil when i set it to "testtesttest"?

EDIT: The error is thrown by: setText("testtesttest")

Thanks in advance!

JDev
  • 124
  • 1
  • 9
  • 2
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) –  Jul 22 '16 at 15:45
  • @PetahChristian The question i asked is different then the one u think its a duplicate of... i edited it to be more specific – JDev Jul 22 '16 at 15:51
  • It's not different. Your crash happens since your `patt` implicitly unwrapped optional is nil, and that is covered by the dupe target. –  Jul 22 '16 at 16:01

2 Answers2

1

Try this:

fun test() {
   guard patt != nil else {
     print("patt doesn't exist!")
     return
   }
   patt.setText("testtesttest")
}

Odds are patt is nil. Wait until awakeFromNib has been called to go looking for any outlets. Also, since you say this is from a notification wrap the set text in a dispatch block to put it on the main thread.

theMikeSwan
  • 4,739
  • 2
  • 31
  • 44
1

Your error starts here:

let controller = InterfaceController()

You instantiate an interface controller. Yet it's not instantiated from a storyboard, so its outlets won't be hooked up to any scene.

Then you try to access an implicitly unwrapped optional outlet which never had been connected to any text label, and your program reasonably crashes.

This is covered by the dupe target, under "Implicitly unwrapped optionals."

  • Ok so where should i instantiate the controller? – JDev Jul 22 '16 at 16:01
  • That's a completely unrelated question. I'd suggest researching it first, before posting a new question, to see if anyone else has *already* asked or answered that. –  Jul 22 '16 at 16:04