我正在尝试将WebView迁移到WKWebView并遇到异常Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
这是在webView.load(req)
上抛出的
这是我的WebView
import OAuthSwift
import UIKit
typealias WebView = UIWebView // WKWebView
class WebViewController: OAuthWebViewController {
var targetURL: URL?
let webView: WebView = WebView()
override func viewDidLoad() {
super.viewDidLoad()
self.webView.frame = UIScreen.main.bounds
self.webView.scalesPageToFit = true
self.webView.delegate = self
self.view.addSubview(self.webView)
loadAddressURL()
}
override func handle(_ url: URL) {
targetURL = url
super.handle(url)
self.loadAddressURL()
}
func loadAddressURL() {
guard let url = targetURL else { return }
let req = URLRequest(url: url)
self.webView.loadRequest(req)
}
}
// MARK: delegate
extension WebViewController: UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.url, url.scheme == "oauth-discogs" {
// Call here AppDelegate.sharedInstance.applicationHandleOpenURL(url) if necessary ie. if AppDelegate not configured to handle URL scheme
// compare the url with your own custom provided one in `authorizeWithCallbackURL`
self.dismissWebViewController()
}
return true
}
}
这是我目前为WKWebView
import UIKit
import WebKit
import OAuthSwift
class WKWebViewController: OAuthWebViewController, WKUIDelegate {
var targetURL: URL?
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView?.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .purple
loadAddressURL()
}
override func handle(_ url: URL) {
targetURL = url
super.handle(url)
self.loadAddressURL()
}
func loadAddressURL() {
guard let url = targetURL else { return }
print(url)
let req = URLRequest(url: url)
print(req)
webView.load(req)
}
}
extension WKWebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
title = webView.title
}
}
loadAddressURL
中的print语句正在输出预期的URL,但是我完全无法解决问题。
目前是否可以为此目的使用WKWebView
?
我认为没有shouldStartLoadWith
可能会导致此问题,我该如何重写?任何帮助我们都非常感谢。