I use Swift4.0 and Xcode9.0. I try to show a website using WKWebView. It had no problem until yesterday, but today an error occurred.
import UIKit
import WebKit
class WKWebViewViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
var startUrl = "https://www.apple.com"
var requestUrl: String?
override func loadView() {
webView.uiDelegate = self
webView.navigationDelegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
webView.allowsBackForwardNavigationGestures = true
if let url = URL(string: startUrl) {
let request = URLRequest(url: url)
webView.load(request)
}
}
}
The error occurs at webView.uiDelegate = self. Here's the error log:
fatal error: unexpectedly found nil while unwrapping an Optional value
For debug, I added print("webView:\(webView)") under loadView(), and I found webView itself is nil.
I tried to add ? to all webView, but only black screen appeared on the app.
Why WkWebView becomes nil? Is it some required setting outside my code?
You must call super.loadView() when you override loadView this way. This is why the WKWebView is nil.
The docs suggest not overriding loadView at all when using a storyboard/xib
If you use Interface Builder to create your views and initialize the view controller, you must not override this method.
You should move those 2 lines of code as the second thing in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With