我们在生产中检测到,有时我们尝试设置 WKWebView 的 WKNavigationDelegate,但即使我们分配给委托的对象不是 nil,并且是 WKNavigationDelegate 命令结果的有效分配实例设置委托是网络视图的委托保持为零。
基本上一步一步发生的是:
我们在日志中观察到,在约 7% 的情况下,webview.navigationDelegate 等于 nil,即使在将完全分配的 WKNavigationDelegate 对象分配给实例后也是如此。
我们设置委托的类:
import WebKit
class WebViewContainer: NSObject {
private static var sharedInstance: WebViewContainer?
let webView: WKWebView
var webViewContainerNavigationDelegate: WKNavigationDelegate?
var webViewContainerUIDelegate: WKUIDelegate?
// Use this standard init function to create a new instance
init(config: WKWebViewConfiguration?) {
if let configExists = config {
self.webView = WKWebView(frame: .zero, configuration: configExists)
} else {
self.webView = WKWebView()
}
super.init()
self.webView.navigationDelegate = self
self.webView.uiDelegate = self
}
// Use this shared function to use a Singleton instance
static func shared(config: WKWebViewConfiguration?) -> WebViewContainer {
guard let existingInstance = sharedInstance else {
let newShared = WebViewContainer(config: config)
sharedInstance = newShared
return newShared
}
return existingInstance
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WebViewContainer: WKNavigationDelegate {
// Implemented WKNavigationDelegate here
}
请注意,创建这个 Container 类是为了测试使用 Singleton WKWebView 时成功率是否有所提高,但这并没有提高结果。
不幸的是,我无法在本地重现此问题,但我可以从我们的日志中看到,在大约 7% 的情况下,我们的用户会受到此问题的影响。
有人见过这样的问题吗?或者有任何关于如何确保 WKNavigationDelegate 在 100% 的时间内正确分配的提示吗?