Tareq Jami
Tareq Jami

Reputation: 99

handling external links in swift UIWebKit?

I'm working on a webview using swift 4. I'm loading local html files, in these pages are some links to other websites, but once I click on any of them I want to load them in safari or default browser instead of the WebView (browser).

my webView is called "browser"

Here are my ViewController.swift codes:

import UIKit
import WebKit

class ViewController: UIViewController {

@IBOutlet weak var browser: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    let htmlpath = Bundle.main.path(forResource: "kusrc/index", ofType: "html")
    let url = URL(fileURLWithPath: htmlpath!)
    let request = URLRequest(url: url)
    browser.load(request)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}





}

Could somebody help me out? most of the results in google were not what I needed...

Is there the possibility to make an if sentence, where it gets asked if the stringprefix ="http:// or https://" then open safari, otherwise "browser"

Upvotes: 1

Views: 1351

Answers (1)

palme
palme

Reputation: 2629

I think you are looking for this delegate method:

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
        }

        UIApplication.shared.open(url)
        decisionHandler(.cancel)
    } else {
        decisionHandler(.allow)
    }
}

If you want to differentiate according the URL scheme, you can use URLComponents to split the URL in its parts.

let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if components?.scheme == "http" || components?.scheme == "https" {
    // insert your code here
}

// edit (a bit more detailed):

  1. import WebKit on the very top of your class: import WebKit
  2. Make your class compliant to the WKNavigationDelegate, by adding it behind the parent class: class ViewController: UIViewController, WKNavigationDelegate
  3. Assign your class to the navigation delegate of the WKWebView: browser.navigationDelegate = self
  4. Add the above code to your class

A gist of how your class should look like in the end: WKWebView open links in Safari

And here is a very nice tutorial about the topic: https://www.hackingwithswift.com/example-code/wkwebview/how-to-control-the-sites-a-wkwebview-can-visit-using-wknavigationdelegate

Upvotes: 1

Related Questions