Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

ios - 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 target="_blank" or if the URL contains http://, https://, or mailto: 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 {
        webView.loadRequest(navigationAction.request)
    }
    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: "http://www.iSecurityPlus.com") {
     UIApplication.sharedApplication().openURL(requestUrl)
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Code updated for iOS 10 Swift 3:

override func loadView() {
    super.loadView()
    self.webView.navigationDelegate = self 
    self.webView.uiDelegate = self  //must have this
}

func webView(_ webView: WKWebView,
               createWebViewWith configuration: WKWebViewConfiguration,
               for navigationAction: WKNavigationAction,
               windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil, let url = navigationAction.request.url {
      if url.description.lowercased().range(of: "http://") != nil ||
        url.description.lowercased().range(of: "https://") != nil ||
        url.description.lowercased().range(of: "mailto:") != nil {
        UIApplication.shared.openURL(url)
      }
    }
  return nil
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...