iOS wkwebview 监听wkwebview的网络请求
要监听 iOS 的 WKWebView 的网络请求,你可以使用 WKNavigationDelegate 协议的一些方法来实现。以下是一个示例代码,展示了如何监听 WKWebView 的网络请求:
首先,确保你的视图控制器遵循 WKNavigationDelegate 协议:
class ViewController: UIViewController, WKNavigationDelegate {
// ...
}
然后,在你的视图控制器中实现 WKNavigationDelegate 的方法:
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.bounds)
webView.navigationDelegate = self
view.addSubview(webView)
// 加载一个网页
if let url = URL(string: "https://www.example.com") {
webView.load(URLRequest(url: url))
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("网页加载完成")
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("开始加载网页")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("网页加载失败:\(error.localizedDescription)")
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
print("网页重定向")
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
print("网页开始接收内容")
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("收到身份验证挑战")
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
这些方法中的大部分都是可选的,你可以根据你的需要实现其中的一些或全部
原文地址: https://www.cveoy.top/t/topic/iTmb 著作权归作者所有。请勿转载和采集!