0

How do i get my WKWebview browser to open links in the same browser, currently if i click a link it doesnt do anything and only lets me open it in safari. How can i fix this so that when a link is clicked it opens in the same WkWebView browser?

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    //Web View
    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://tweetdeck.twitter.com/")
        let request = URLRequest(url: url!)

        webView.load(request)
        webView.navigationDelegate = self

    }
  • Possible duplicate of -> https://stackoverflow.com/questions/36231061/wkwebview-open-links-from-certain-domain-in-safari – Keshu R. Dec 07 '19 at 07:28

1 Answers1

0

Please try this code use decidePolicyFor method of WKNavigationDelegate

extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated {
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }

        let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
        if components?.scheme == "http" || components?.scheme == "https"
        {
            UIApplication.shared.open(url)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    } else {
        decisionHandler(.allow)
    }
}}
kishor soneji
  • 795
  • 1
  • 9
  • 16
  • it just brings me to safari, i want it to load in the browser that i clicked the link in @kishor soneji –  Dec 07 '19 at 07:14
  • I check your code by default is loaded in WKWebview @user12494754 when click on button also they reload same wkwebview – kishor soneji Dec 07 '19 at 07:35
  • before adding your code, when i click the link it just did nothing @kishor soneji –  Dec 07 '19 at 07:44