我目前正在使用 WKWebView 编写一个 Web 视图应用程序,当加载页面时没有互联网连接时,它应该显示一个自定义错误页面。我试图通过调用 WKNavigationDelegate 的方法来处理这个问题,但它从未被调用过。我是 Swift 新手,我已经尝试了一些在 stackoverflow 上找到的解决方案,但没有一个对我有用。难道我做错了什么?
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError)
{
let url = Bundle.main.url(forResource: "no_connection", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}