1

I'm trying to launch Safari browser when a user click on a link or URL within a webView.

I have a viewcontroller with a webView which loads a request. On the webView there's a link that if clicked, Safari would launch. I've set the webView as a delegate. But it doesn't seem to work. It always load the link in the embedded view. Some of the answers I found on here are old object-c codes and they don't work. I'm hoping if anyone can help.

Thanks.

import SafariServices
import UIKit
import WebKit

class AboutViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var spinner: UIActivityIndicatorView!
    @IBOutlet weak var webView: WKWebView!




    override func viewDidLoad() {
        super.viewDidLoad()

        // Start the spinner
        spinner.alpha = 1
        spinner.startAnimating()

        //Set delegate for the webview
        webView.navigationDelegate = self

    }

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

    override func viewWillAppear(_ animated: Bool) {


        let path = Bundle.main.path(forResource: "about", ofType: "html")

        guard path != nil else {  //Guard statement is good to check whether something is true.  So in this case, it reads "confirm if path is not nil else do something else"
            print("Error: Can't find the file")
            return
        }


        //Create a url object from the string path
        let url = URL(fileURLWithPath: path!)
        //Create a request
        let request = URLRequest(url: url)

            //Load the request
            webView.load(request)


    }

    func webView(_: WKWebView, shouldStartLoadWith: URLRequest, navigationType: WKNavigationType ) -> Bool {

    if navigationType == WKNavigationType.linkActivated {
        UIApplication.shared.open(shouldStartLoadWith.url!, options: [:], completionHandler: nil)

        return false
    }

    return true
   }

}
Mrfroddo
  • 49
  • 6
  • 1
    You are using `WKWebView` but made a `UIWebView`'s delegate method. – Ryan Jun 27 '18 at 21:24
  • 1
    Change your `guard` to `guard let path = path else {` then you don't need to force unwrap `path` in the rest of the block. – rmaddy Jun 27 '18 at 21:26

1 Answers1

1

I'm using this thread (WKWebView open links from certain domain in safari) to make it work.

Here is the answer:

import SafariServices
import UIKit
import WebKit

class AboutViewController: UIViewController, WKNavigationDelegate {

@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var webView: WKWebView!


override func viewDidLoad() {
    super.viewDidLoad()

    // Start the spinner
    spinner.alpha = 1
    spinner.startAnimating()


    let path = Bundle.main.path(forResource: "about", ofType: "html")

    guard path != nil else {  //Guard statement is good to check whether something is true.  So in this case, it reads "confirm if path is not nil else do something else"
        print("Error: Can't find the file")
        return
    }

    //Create a url object from that string path
    let url = URL(fileURLWithPath: path!)






    //Set delegate for the webview
    webView.navigationDelegate = self

     //Load the request
    webView.load(URLRequest(url: url))

}

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

override func viewWillAppear(_ animated: Bool) {



}







func webView(_ webView: WKWebView,  decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated  {
        if let url = navigationAction.request.url,
            let host = url.host, !host.hasPrefix("www.google.com"),
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
            //print(url)
           // print("Redirected to browser. No need to open it locally")
            decisionHandler(.cancel)
        } else {
           // print("Open it locally")
            decisionHandler(.allow)
        }
    } else {
        //print("not a user click")

        decisionHandler(.allow)
    }
}


func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    spinner.stopAnimating()
    spinner.alpha = 0

}

}

Mrfroddo
  • 49
  • 6