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

I know this question is asked many times over here but I have tried all the solutions but none of them helped me out. I am getting error in this line

myWebView.load(URLRequest(url: url))

I am using navigation controller and segue performs programatically when the user defaults are available from below


class ViewController: UIViewController {

let defaults = UserDefaults.standard
var username = ""
var password = ""

override func viewDidLoad() {
    super.viewDidLoad()
    
    if(defaults.bool(forKey: "isLoggedin") == true){
        username = defaults.string(forKey: "username") ?? ""
        password = defaults.string(forKey: "password") ?? ""
    
        if(username != "" && password != ""){
            self.navigationController?.pushViewController(WebViewViewController(), animated: true)
        }
    }
}

}

Following is my webview uiViewController

import WebKit

class WebViewViewController: UIViewController {
@IBOutlet weak var myWebView: WKWebView!

let defaults = UserDefaults.standard
var username = ""
var password = ""

override func viewDidLoad() {
    super.viewDidLoad()
    //myWebView = WKWebView()
    
    navigationController?.setNavigationBarHidden(true, animated: true)
    
    if(defaults.bool(forKey: "isLoggedin") == true){
        username = defaults.string(forKey: "username") ?? ""
        password = defaults.string(forKey: "password") ?? ""
    
        if(username != "" && password != ""){
            guard let url = URL(string: "https://google.com") else {return}
            myWebView.load(URLRequest(url: url))
        }
    }
    
}
}

My story board screen shot

Try this:

guard let url = URL(string: "https://www.google.com") else {return}

Otherwise, "myWebView" must be nil.
You could add a diagnostic message, before the error line...

print("myWebView: \(myWebView)")

Usually, that happens when the object (here MyWebView) in storyboard is not properly connected to its IBOutlet.

So, check the connection.

  • If not set, do it
  • if set (which seems to be the case as the name My Web View appears in objects list), disconnect it (right click on My Web View) and reconnect
  • Do a clean build folder.

I tested with your code, creating a small webview.

            guard let url = URL(string: "https://google.com") else {return}
            myWebView.load(URLRequest(url: url))

and it works perfectly.

So problem is not the url, it il likely the connection.

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