-1

I am trying to open a link sent in my local notification userInfo in my WKWebView, i already tried several different options of casting Optional to String, but still no luck, i even tried to check typeof variable i am passing, to be sure it's not Optional anymore, but webView.load still produces fatal, this is my final variant, minimized as much as possible to help reproduce whole situation

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {



    if let userInfo = response.notification.request.content.userInfo as? Dictionary<String,String> {
        if let link = userInfo["link"] {
            let url = URL(string: link)!

            print(type(of: url));
            print(url);

            let urlRequest = URLRequest(url: url);
            ViewController().webView.load(urlRequest)
        }
    }

    completionHandler();
}

still

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value from ViewController().webView.load(urlRequest) link is just https://google.com

output to console from print is

URL // typeof url
https://google.com // url
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79
  • what is this: `ViewController().webView.load(urlRequest)`? – holex Mar 07 '18 at 14:21
  • 1
    This is Swift, it's unnecessary to use semicolons at the end of lines. – Tamás Sengel Mar 07 '18 at 14:23
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Dávid Pásztor Mar 07 '18 at 14:25

1 Answers1

1

You are trying to create a new ViewController after receiving a notification. If this is intended, this is not the right way to create a new ViewController (you need to instantiate it from a storyboard or a xib file and then present it in some way). In your case you're simply creating a new instance of the ViewController class without the associated view, so your application is most likely crashing because the webView property is nil.

If this is not indented and your ViewController is already presented on the screen in some way, you need to pass this dictionary to the already existing ViewController and this ViewController should then open your link. I suggest using NSNotificationCenter for this.

FruitAddict
  • 2,042
  • 15
  • 16
  • Thank you, i ll try to use `storyboard` variant, and will post results later, if you interested, here is a bit more about my code https://stackoverflow.com/questions/49151071/wkwebview-open-url-on-local-notification-tap/49151308?noredirect=1#comment85306865_49151308 – Itsmeromka Mar 07 '18 at 14:28
  • 1
    Remember to present it on the screen, creating an instance from a storyboard will do nothing by itself. – FruitAddict Mar 07 '18 at 14:51