12

I can't find solution for this. I hope You'll help me. I want buttons with hyperlinks to open websites in webview on second screen. Hyperlink opens in safari and I want it to open on second screen in webview. Thank you

Simon Walachowski
  • 131
  • 1
  • 1
  • 9
  • 1
    Possible duplicate of [How do I add a UIWebView to my iOS app?](http://stackoverflow.com/questions/5408746/how-do-i-add-a-uiwebview-to-my-ios-app) – JAL Oct 26 '16 at 13:56

3 Answers3

19

You can use SFSafariViewController to open link in your application, here is the code for that

First you need to import SafariServices

import SafariServices

then on the button action, you can open SFSafariViewController

For swift 3.0

let svc = SFSafariViewController(url: URL(string:"http://stackoverflow.com")!)
self.present(svc, animated: true, completion: nil)
Rajat
  • 10,977
  • 3
  • 38
  • 55
  • 1
    `NSURL(string: "http://stackoverflow.com")! as URL)` why not just `URL(string: "http://stackoverflow.com")!`? – JAL Oct 26 '16 at 13:55
  • @JAL I am quite new to swift, thank for correcting me :) – Rajat Oct 26 '16 at 13:58
  • @JAL if you do the code in swift3 then you can write like that – Sanjeet Verma Oct 26 '16 at 13:58
  • 1
    oh my god, this must be the 3rd time a solution was extremely simple but so hard to find on the internet because the practices and available tools keep changing and 90% of answers are outdated! Eveone else is saying we have to implement our own UIWebView – pete Jul 16 '17 at 04:38
6

Swift 4.1 and Swift 5. If there are some links inside the app then it will open in safari, So to opens the links within same webview implement following navigationDelegate fo WKWebView.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
     if navigationAction.navigationType == WKNavigationType.linkActivated {
        webView.load(navigationAction.request)
        decisionHandler(.cancel)
        return
     }
     decisionHandler(.allow)
}
Community
  • 1
  • 1
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58
0

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

        if let url = navigationAction.request.url, let scheme = url.scheme?.lowercased() {

            if scheme == "https" || scheme == "http"{
                if UIApplication.shared.canOpenURL(url){
                    // use the available apps in user's phone
                    UIApplication.shared.open(url)
                }
            }
        }
    decisionHandler(.allow)

}

Deepak Ghadi
  • 163
  • 2
  • 5