Jed Grant Jed Grant - 1 year ago 120
iOS Question

Open a WKWebview target="_blank" link in Safari

I am trying to get my Hybrid IOS app that uses Swift and WKWebviews to open a link that has

or if the URL contains
, or
in Mobile Safari.

From this answer I get this code.

func webView(webView: WKWebView!, createWebViewWithConfiguration configuration: WKWebViewConfiguration!, forNavigationAction navigationAction: WKNavigationAction!, windowFeatures: WKWindowFeatures!) -> WKWebView! {
if navigationAction.targetFrame == nil {
return nil

First, that doesn't do anything for me. Second, I want it to open in a new window. And I found this code that is supposed to do something like that...

if let requestUrl = NSURL(string: "") {

How do I put these two together and get them to work? What do I need to add to the ViewController declaration to make it work?

Answer Source

In (from here)

 override func loadView() {
    self.webView.navigationDelegate = self 
    self.webView.UIDelegate = self  //must have this

Then add the function (from here, with additions)...

func webView(webView: WKWebView,
    createWebViewWithConfiguration configuration: WKWebViewConfiguration,
    forNavigationAction navigationAction: WKNavigationAction,
    windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            var url = navigationAction.request.URL
            if url.description.lowercaseString.rangeOfString("http://") != nil || url.description.lowercaseString.rangeOfString("https://") != nil || url.description.lowercaseString.rangeOfString("mailto:") != nil  {
        return nil
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download