我创建了一个名为JSBridge
的类,这个类实现了WKNavigationDelegate
,我在协议方法中做了一些自定义的东西,然后调用另一个UIViewController
的默认WKNavigationDelegate
},例如WebViewController
又名webViewDelegate
,所以我必须这样做
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let webViewDelegate = webViewDelegate , self.webView == webView else {
decisionHandler(.allow)
return
}
//do something here then call `WebViewController`'s implementation
if webViewDelegate.responds(to: #selector(webViewDelegate.webView(_:decidePolicyFor:decisionHandler:))) {
webViewDelegate.webView!(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
} else {
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
guard let webViewDelegate = webViewDelegate , self.webView == webView else {
decisionHandler(.allow)
return
}
//do something here then
if webViewDelegate.responds(to: #selector(webViewDelegate.webView(_:decidePolicyFor:decisionHandler:))) {
webViewDelegate.webView!(webView, decidePolicyFor: navigationResponse, decisionHandler: decisionHandler)
} else {
decisionHandler(.allow)
}
}
我的问题是在xcode8(swift3)中编译器给我错误:
Ambiguous use of 'webView(_:decidePolicyFor:decisionHandler:)'
,它们与编译器具有相同的名称
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
答案 0 :(得分:2)
您可以使用as
从一些不明确的方法中选择一个:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let webViewDelegate = webViewDelegate , self.webView == webView else {
decisionHandler(.allow)
return
}
typealias WKNavigationActionMethodType = (WKWebView,WKNavigationAction,@escaping(WKNavigationActionPolicy)->Void) -> Void
if webViewDelegate.responds(to: #selector(webView(_:decidePolicyFor:decisionHandler:) as WKNavigationActionMethodType)) {
webViewDelegate.webView!(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
} else {
decisionHandler(.allow)
}
}
另一种处理此类情况的方法是"避免使用responds(to:)
并使用可选链接":
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let webViewDelegate = webViewDelegate , self.webView == webView else {
decisionHandler(.allow)
return
}
if webViewDelegate.webView?(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler) == nil {
decisionHandler(.allow)
}
}
委托方法的返回类型为Void
,因此其可选链接结果的类型为Void?
。在您的情况下,仅当实例中未实现可选方法时,它才会变为nil
。因此,将结果与nil
进行比较是检查可选方法是否已实现(并实际调用)。