-1

I'm trying to detect clicks on links in a WKWebView and load the corresponding URLs in another WKWebView. I'm able to get the URL of the click and create a URL request but loading the URLRequest always fails with the same error:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.

This is very strange because when I print the value of the URLRequest variable, I can see that it's not nil at all.

let navigationController = self.navigationController
self.navigationController?.setToolbarHidden(false, animated: false)
let autoLinkUrl = (messageBody!["autoLinkUrl"] as? String)!
print(autoLinkUrl) /* prints: https://news.ycombinator.com/ */
            
if let requestURL = URL(string: autoLinkUrl) {
  print(requestURL) /* prints: https://news.ycombinator.com/ */
  let request : URLRequest? = URLRequest(url: requestURL)
  print(request) /* prints: Optional(https://news.ycombinator.com/) */
  self.websiteRecordingVC!.webView.load(request!) /* Fatal error is raised here */
  navigationController!.pushViewController(self.websiteRecordingVC!, animated: true)
}

Any help would be welcome. Many thanks.

  • 2
    Maybe `self.websiteRecordingVC` is `nil` ? – gcharita Sep 01 '20 at 23:34
  • 1
    Get rid of that ! on the websiteRecordingVC!. For views, you should never use it. Make sure you are connecting it properly on your storyboard or that your instantiating it properly if you're creating your views programatically. – Jacob Sep 01 '20 at 23:37
  • The websiteRecordingVC variable is working properly. I'm able to switch between the different view controllers without problems (besides this autolink use case). Removing the "!" from websiteRecordingVC! gives a new error, so I'm not sure that will solves my issues. Since it's working as it is in other parts of the app, I think it's better to keep it as it is. Thanks for your help! – Ismaël Sow Sep 01 '20 at 23:59
  • https://stackoverflow.com/help/minimal-reproducible-example – Chris Sep 03 '20 at 08:49

1 Answers1

0

In your code you are force-unwrapping (!) every other optional unnecessarily which is highly Not Recommended. Over-using the force-unwrapping is not a good coding practise. It may result into unexpected crashes in your app.

You must use optional binding (if-let) and optional chaining for gracefully handling the optionals.

if let requestURL = URL(string: autoLinkUrl) {
    let request = URLRequest(url: requestURL)
    if let vc = self.websiteRecordingVC {
        vc.webView.load(request)
        navigationController?.pushViewController(vc, animated: true)
    }
}

Also, in your websiteRecordingVC check if all the IBOutlets are connected properly.

PGDev
  • 23,751
  • 6
  • 34
  • 88