iosswiftxcodeurlrequestswift-optionals

Unwrapped URLRequest is always nil


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.


Solution

  • 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.