Unable to open external link in safari using WKWebView

241 views Asked by At

I am migrating from UIWebView to WKWebView. Need to load HTML content in WKWebView everything is working fine but the problem is unable to open link in the external safari browser after a click on any link from WKWebView. I used below code

Class

class CTFSPolicyAndTermsViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {}

outlet and WKWebView variable

  @IBOutlet weak var webViewContainer: UIView!
  var webView: WKWebView!

viewDidLoad method

    override func viewDidLoad() {
    super.viewDidLoad()
    webView = WKWebView()
    self.webView.uiDelegate = self
    self.webView.navigationDelegate = self

    let webConfiguration = WKWebViewConfiguration()
    webView =  WKWebView(frame: .zero, configuration: webConfiguration)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webViewContainer.addSubview(webView)
   [webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor),
    webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor),
    webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor),
    webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor)].forEach  { 
     anchor in
    anchor.isActive = true
    }

for loading the HTML Content

     if(self.isTermsMode)
        {

            let path:String = Bundle.main.path(forResource: "abc", ofType: "html")!
            let text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
            webView!.loadHTMLString(text!, baseURL: nil)
        }

decidePolicyFor

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url {
            print(url)
            UIApplication.shared.open(url)  
            decisionHandler(.cancel)
        } else {
        decisionHandler(.allow)
       }
    }

decidePolicyFor method should call but it's not executing I am unable to find the problem

1

There are 1 answers

0
sham On BEST ANSWER

i was missing the order

let webConfiguration = WKWebViewConfiguration()
    webView =  WKWebView(frame: .zero, configuration: webConfiguration)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webViewContainer.addSubview(webView)
    [webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor),
     webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor),
     webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor),
     webView.rightAnchor.constraint(equalTo: 
      webViewContainer.rightAnchor)].forEach  { anchor in
        anchor.isActive = true
    }
    self.webView.uiDelegate = self
    self.webView.navigationDelegate = self