3

Could anyone help me in understanding why my webView is not getting initialized here. I am getting the following error because webView is nil.

Fatal error: Unexpectedly found nil while unwrapping an Optional value

What exactly I am missing here?

import UIKit
import WebKit


class MemoriesViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear( animated )

        let urlString:String = "https://www.apple.com"
        let url:URL = URL(string: urlString)!
        let urlRequest:URLRequest = URLRequest(url: url)
        webView.load(urlRequest)

    }


    }

}

Screenshot for better clarity where the error is actually happening:

enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
python
  • 4,403
  • 13
  • 56
  • 103

3 Answers3

9

Add Webkit.Frameworks to Linked Framework and Libraries

enter image description here

You can then add the Outlet for WKWebView and use your code

import UIKit
import WebKit

class MyWebViewController: UIViewController {

@IBOutlet weak var myWV: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    let urlString:String = "https://www.apple.com"
    let url:URL = URL(string: urlString)!
    let urlRequest:URLRequest = URLRequest(url: url)
    myWV.load(urlRequest)
}


}
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25
  • You are my life saver. I spent about 2 hours to figure out this problem. **MUST add Webkit.framework**. – cadenzah May 09 '19 at 13:47
5

In Xcode 10, you can foll bellow the step:

  1. Click the project
  2. Go to build phase
  3. Go to Link Binary with Libraries
  4. Click add plus sing under Link Binary with Libraries
  5. open a windows & search Webkit.framework
  6. add & enjoy it
  7. Show bellow image enter image description here
Enamul Haque
  • 4,789
  • 1
  • 37
  • 50
1

The problem was my output was not connected to the storyboard. That's why @IBOutlet was not getting initialized.

python
  • 4,403
  • 13
  • 56
  • 103