WKWebView target="_blank" link open new tab in safari ios11, swift 4
I have pasted some sample code of a WKWebView project (load local html from folder) that requires links that have target=_blank
to open in a new browser window.
I have highlighted the 3 things you must have to get links to open correctly.
class ViewController extends WKUIDelegate
self.webView.uiDelegate = self
- Use
UIApplication.shared.open
instead ofwebView.load
Let me know it it works and if anyone can suggest improvements to the sample code below, that would help me too :)
Full sample code for Xcode 9.2, Swift 4 below.
Good Luck
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.uiDelegate = self
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")
let htmlUrl = URL(fileURLWithPath: htmlPath!)
let htmlDir = Bundle.main.url(forResource: "www", withExtension: nil)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlDir!)
}
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
//webView.load(navigationAction.request)
UIApplication.shared.open(navigationAction.request.url!, options: [:])
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden: Bool {
return true
}
}