Get parameters from a link in a webview

1.5k views Asked by At

I have created a webview in a viewController and loading a page like this

func loadAddress(){
    let requestURL = NSURL(string:"http://www.example.com/")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.loadRequest(request as URLRequest)
}

And calling this in

viewDidLoad

I have somelinks in the page with URL parameters like this

http://www.example.com?id=1&title=ABC

Now when a user clicks this link from the app then instead of redirecting to URL, I want to get the parameters from URL and open a dialog box in iOS

I have found some examples in Objective C but I am looking for a solution in Swift 3

PS: I have access to this website's HTML I can replace links as required by Xcode

EDIT: Here is what i have tried, in the same file where my webview is i wrote this function

func webView(_ webView: UIWebView,shouldStartLoadWith request: URLRequest,navigationType: UIWebViewNavigationType) -> Bool {

    let scheme = request.url!
    NSLog(scheme.absoluteString)

    return false

}

and also made sure that the class is a delegate to webview

enter image description here

what am i doing wrong?

2

There are 2 answers

16
AudioBubble On

you should handle the webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool method, that takes the URLRequest as a parameter. In this method you can do whatever you want to that URL.

Don't forget to set your class as the delegate of the webview.

If you want to play with the query string, you can get inspiration from this objective-c answer

0
Wasif Khalil On

I have found a solution myself, the code i had written was correct, i just had to make sure that my class also implements UIWebViewDelegate

so the class looks like this

class Mainbillboard: UIViewController,UIWebViewDelegate {


@IBOutlet weak var activity: UIActivityIndicatorView!
@IBOutlet weak var webview: UIWebView!


override func viewDidLoad() {
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    loadAddress()
}

func loadAddress(){
    let requestURL = NSURL(string:"example.com")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.loadRequest(request as URLRequest)

}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let scheme = request.url!
    NSLog(scheme.absoluteString)
    NSLog("here it worked!!")

    return true

}


func webViewDidStartLoad(_:UIWebView){
    self.view.bringSubview(toFront: self.activity)
    activity.startAnimating()
    NSLog("Indicator is loading")

}

func webViewDidFinishLoad(_:UIWebView){
    activity.stopAnimating()
    NSLog("Indicator stopped loading")
}

}