Sajib Ghosh
Sajib Ghosh

Reputation: 418

How to open social link by clicking on button inside WKWebView

There is a social link button inside WKWebView. When I click on the button nothing happens.

Could you please tell me how to open the link by clicking on the button?

Thanks in advance.

Upvotes: 0

Views: 829

Answers (2)

SCS
SCS

Reputation: 435

what link u want to open change "facebook","twitter" and you can add more links also

     func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated  {
        if let url = navigationAction.request.url ,UIApplication.shared.canOpenURL(url)  {
            //    let urlString = try! String(contentsOf: url)
            if (url.absoluteString.range(of: "facebook.com") != nil || url.absoluteString.range(of: "twitter.com") != nil){

               //UIApplication.shared.open(url)
                print("Redirected to browser. No need to open it locally")
                decisionHandler(.cancel)
            }else{
                print("Open it locally")
                decisionHandler(.allow)
            }
        }

Upvotes: 4

Helen Wood
Helen Wood

Reputation: 1882

You need a on click listener.

You can use WKWebView to display interactive web content in your app. Ideal for displaying HTML markup, styled text content, or complete web pages. After that, you need to handle the Social button you're calling and the data submitted if any...

Responding To WKWebView Events With WKNavigationDelegate

A WKWebView web view has two main delegate protocols and properties:

  • navigationDelegate of type WKNavigationDelegate, which responds to navigation events
  • uiDelegate of type WKUIDelegate, which responds to user interaction events

Of these two delegate protocols, the WKNavigationDelegate is probably used most frequently. So, let’s hook into some page navigation events! We’ll do so with these delegate functions:

webView(_:didStartProvisionalNavigation:)
webView(_:didCommit:)
webView(_:didFinish:)
webView(_:didFail:withError:)
webView(_:didFailProvisionalNavigation:withError:)

First, let’s adopt the protocol and set the webView delegate. Here’s how:

  1. Add the WKNavigationDelegate protocol to your view controller’s class declaration, like: class WebViewController: UIViewController, WKNavigationDelegate

  2. Set the navigationDelegate property of webView to self, before loading the web request, like: webView?.navigationDelegate = self

Next, implement the five delegate functions described earlier. Set their function bodies to print(#function), so we can see the order in which the functions are called.

Like this:

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
{
    print(#function)
}

Upvotes: 0

Related Questions