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
}
}