dwinnbrown
dwinnbrown

Reputation: 4029

Swift - Opening web view links modally

So I have a web view displaying a page and would like to open any links in a new view controller containing a web view modally (like twitter and Facebook do).

I have worked out how to get the url of the link clicked:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let youClicked = request.URL!
    print(youClicked)
    return true
}

But haven't managed to work out how I can pass this value into a web view on another page and present that view controller modally as a popover.

Any ideas?

Upvotes: 2

Views: 6303

Answers (2)

charlyatwork
charlyatwork

Reputation: 1197

There isn't an out of the box component which can deal with your need. Instead you have to create your own component:

  1. Create a new UIViewController and place a WKWebView in it (Can be archived by Interface Builder or Code - I usually prefer Interface Builder) . Furthermore create an outlet (e.g. called "webView") for the WKWebView

  2. Create the controller - set the URL and present it // Create the controller let controller = storyboard.instantiateViewControllerWithIdentifier("MyCustomWebViewController") //start loading the URL controller.webView.loadRequest(request) // present it presentViewController(viewController, animated: true, completion: nil)

Upvotes: 1

Adolfo
Adolfo

Reputation: 1862

Take a look at SFSafariViewController at Apple Developer Documentation

In order to implement the solution you have to import SafariServices and after that...

  1. Declare an Safari View Controller

    let destination: NSURL = NSURL(string: "http://desappstre.com")!

    let safari: SFSafariViewController = SFSafariViewController(URL: destination)

  2. Segue from your current view controller to the safari view controller declared on step 1

    self.presentViewController(safari, animated: true, completion: nil)

If you need control over HTTP events you can use the SFSafariViewControllerDelegate in your destination view controller.

Upvotes: 6

Related Questions