Search code examples
webviewwkwebviewswift5wkwebviewconfiguration

URL is not opening in WKWebView in swift


I have a requirement to open the URL in WKWebView and login to the portal. As user logged in successfully after that I have to perform download operation from WKWebView, Everything is working fine but it's opening in external safari browser but as per requirement it should open in WKWebView

Outlet for WKWebView

@IBOutlet var webView: WKWebView!

Function to call URL in WKWebVIew

   func loadURLInWebView() {
   let url = URL(string: "https://www-qa.yyy.com/content/dash/en/public/login.html")
   let urlRequest = URLRequest(url: url!)
   if let webView = webView {
       webView.load(urlRequest)
   }
}

after adding decidePolicyFor delegate it's opening url in safari but it should open in WKWebView. I am not able to find the issue.

 public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    let url = navigationAction.request.url
    guard url != nil else {
        print(url!)
        decisionHandler(.allow)
        return
    }

    if url!.description.lowercased().starts(with: "http://") ||
        url!.description.lowercased().starts(with: "https://")  {
        decisionHandler(.cancel)
        UIApplication.shared.open(url!, options: [:], completionHandler: nil)
    } else {
        decisionHandler(.allow)
    }
}

Solution

  • you are handling guard statement in the wrong way. In guard else, the condition will be called when the URL is nil. If you do print(URL!) in else your app will crash. moreover when URL is nill, you should call cancel Handler.

    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    
        guard let url = navigationAction.request.url else { // else will be called when url is nil
           decisionHandler(.cancel)
           return
        }
    
        if url.description.lowercased().starts(with: "http://") ||
           url.description.lowercased().starts(with: "https://")  {
               decisionHandler(.allow)
        } else {
              decisionHandler(.cancel)
               UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }