Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift How to make links open in Webview?

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

like image 944
Simon Walachowski Avatar asked Oct 26 '16 13:10

Simon Walachowski


2 Answers

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)
like image 101
Rajat Avatar answered Sep 21 '22 16:09

Rajat


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)
}
like image 33
Gurjinder Singh Avatar answered Sep 22 '22 16:09

Gurjinder Singh