Tom Tom - 2 months ago 194
Swift Question

WKWebView Delegate (decidePolicyFor) issues in Swift 3.0

I am currently implementing a WKWebView into my application and I want to use the decidePolicyFor delegation method to decide how my app responds to external links.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {


if navigationAction.navigationType == WKNavigationType.linkActivated && !(navigationAction.request.url?.host?.lowercased().hasPrefix("www.example.com"))! {
UIApplication.shared.open(navigationAction.request.url!, options: [:], completionHandler:nil)
decisionHandler(.allow)

}
else
{
decisionHandler(.cancel)
}


}


However the compiler is giving me the following issue in swift 3.0 :-


Instance method 'webView(:decidePolicyFor:decisionHandler:)' nearly matches optional requirement 'webView(:decidePolicyFor:decisionHandler:)' of protocol 'WKNavigationDelegate'


Does anybody know the solution to this and more importantly why this is happening

Thanks in advance

Answer

When you find something odd in Xcode, please check the latest reference. (Some of the references may not be up-to-date, but luckily, the description of the delegate method seems to be up-to-date.)

Declaration

optional func webView(_ webView: WKWebView, 
      decidePolicyFor navigationAction: WKNavigationAction, 
      decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

Add @escaping after decisionHandler:.

func webView(_ webView: WKWebView,
             decidePolicyFor navigationAction: WKNavigationAction,
             decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
Comments