Search code examples
iosswifthttp-redirectwkwebview

WKWebView - Add a parameter to the URL on redirect in Swift - iOS


I am new to Swift, currently using swift 4.0 and have a very simple app with WKWebView loading a web page.

I have a requirement to append a parameter to a URL when page redirects from one page to another.

I am getting the redirection event in this function:

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

}

But here I am not sure how to update the URL by adding a parameter to it and then do the navigation. Please help in this regard to update the URL before navigating.

I have searched for it and tried to figure out the way to do it but so far I haven't progressed. The navigationAction.action.url is GET only and I am not able to update it.


Solution

  • WKNavigationDelegate, URLComponents

    class ViewerViewController: UIViewController, WKNavigationDelegate  //<--
    // then whenever you call the WKWebView
    //ex: URL = https://en.wikipedia.org/wiki/Main_Page
    
    WKWebView.navigationDelegate = self
    
    
    WKWebView.load(URLRequest)
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    
    
    
    
        print("URL:", navigationAction.request.url)
        if let host = navigationAction.request.url?.path 
         {
             if host.contains("Main_Page")
              {
                  //You can modify this part to form a new url and pass it again.
                  var components = URLComponents()
                  components.scheme = navigationAction.request.url?.scheme
                  components.host =  navigationAction.request.url?.host
                  components.path =  navigationAction.request.url!.path 
                            
                 print("new URL:", components.url!)
                 let customRequest = URLRequest(url: components.url!)
    
                 //change the url and pass it again..
                 WKWebView.load(customRequest) //<--load the new url again..
                 decisionHandler(.cancel) 
            }
            else
            {
                 decisionHandler(.allow) //<-- this will open the page.
            }
         }
         else
         {
             decisionHandler(.allow)
         }
    }