Loc Dai Le
Loc Dai Le

Reputation: 1697

How to add a parameter to all urls in uiwebview

How can I add a parameter to all url detected in uiwebview? I want to append all the url string with this parameter: ?app=1.

Right now I only use 1 UIWebViewDelegate:

func webViewDidFinishLoad(webView: UIWebView) {
}

Is there another delegate I can use to achieve this?

What I have tried:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let url = (request.URL?.absoluteString)! + "?app=1"
    let requestURL = NSURL(string: url)
    let req = NSURLRequest(URL: requestURL!)
    //Load url into WebView container
    //webView.loadRequest(req)


    return true;
}

Upvotes: 1

Views: 3041

Answers (1)

Tobi Nary
Tobi Nary

Reputation: 4596

If it is sufficient to have that done when the link is actually selected by the user , consider altering it in your web view's delegate's

- webView:shouldStartLoadWithRequest:navigationType:

and taking apropriate action, such as returning false and manually load the modified url.

Edit in response to edited question:

try something along these lines (no IDE handy atm):

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

if let url = request.URL {
   if url.absoluteString.rangeOfString("?app=1") != nil {
      // everything is fine. 
      return true
      }
   else {
     let newRequest = // build new request here
     webView.loadRequest(newRequest)
     return false
     }
 }


return true;
}

Upvotes: 1

Related Questions