0

I have UIWebView in my first ViewController, and I want if the user clicks on any link inside UIWebView 1 should open new ViewController (ex. InfoViewController) and passes the URL to new UIWebView inside InfoViewController.

EDIT:

My Storyboard

My Code:

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let url = NSURL (string: "https://google.com");
    let requestObj = NSURLRequest(URL: url!);
    webview.delegate = self;
    webview.loadRequest(requestObj);

}

func webview(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {

    if (navigationType == UIWebViewNavigationType.LinkClicked) {
    //Push to new view controller here and pass new url:
    let url = request.URL
    let infoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("InfoViewController") as! InfoViewController
    infoViewController.passURL = url.absoluteString //Add passURL property in your InfoViewController

    self.navigationController!.pushViewController(infoViewController, animated: true)

    //prevent the current webview from loading the page
    return false
    }

    //webview will load first time normally/other requests will load
    return true
}
Hani
  • 45
  • 1
  • 7

2 Answers2

1

set the webview delegate to self:

webview.delegate = self

And then you can add this delegate method. This runs whenever it tries to load a url. You can add a if check to make sure it is a link they have clicked and run your code to change screen and prevent the current webview from loading the url by returning false:

//Update: got method name wrong:
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {

    if (navigationType == UIWebViewNavigationType.LinkClicked {
         //Push to new view controller here and pass new url:
         let url = request.URL
         let infoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("InfoViewController") as InfoViewController
         infoViewController.passURL = url.absoluteString //Add passURL property in your InfoViewController

         self.navigationController!.pushViewController(infoViewController, animated: true)

         //prevent the current webview from loading the page
         return false
    }

    //webview will load first time normally/other requests will load
    return true
}
Joe Benton
  • 3,703
  • 1
  • 21
  • 17
0
  1. You need to pull the link from your first UIWebview: iPhone - UIWebview - Get the URL of the link clicked
  2. Open the new ViewController and pass the string.
  3. Direct your second UIWebview to open the URL.
Community
  • 1
  • 1
Johnny Rockex
  • 4,136
  • 3
  • 35
  • 55