0

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

import UIKit

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 UIKit
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 shotenter image description here

Tariq
  • 21
  • 1
  • 1
  • 8
  • You’re not using a segue you’re pushing a new instance of the WebViewController. That is causing your crash, as it is expecting the WKWebView to be initialised and it is not. You need to launch your WebViewController from the storyboard. This shows the general idea https://stackoverflow.com/questions/24035984/instantiate-and-present-a-viewcontroller-in-swift – Andrew Feb 12 '22 at 08:41
  • A very common mistake. `WebViewViewController()` creates a brand new instance which is **not** the instance in the storyboard therefore the outlets are not connected. You have to `instantiate` the instance from the storyboard. – vadian Feb 12 '22 at 08:42
  • [This](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu/69686188#69686188) is the answer in the duplicate which is directly related to your question. – vadian Feb 12 '22 at 08:47
  • Thanks @Andrew and vadian. You both saved my day – Tariq Feb 12 '22 at 09:52

0 Answers0