Xcode,Swift; 检测UIWebView中的超链接点击

我用Xcode和Swift制作了一个iOS应用程序。

我想在Safari浏览器中打开特定的超链接,在WebView中有其他的链接。

为了达到这个目的,我将不得不检查超链接何时被点击。

这是迄今为止的代码:

// // PushViewController.swift // App // // import UIKit class PushViewController: UIViewController, UIWebViewDelegate { @IBOutlet var openpushmessage: UIWebView! var weburl:String = "http://www.example.com" override func viewDidLoad() { super.viewDidLoad() let url: NSURL = NSURL(string: weburl)! let requestURL: NSURLRequest = NSURLRequest(URL: url) openpushmessage.loadRequest(requestURL) } override func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == .linkClicked { print("You clicked a hypelink!") } return true } } 

viewDidLoad()的代码打开从我的服务器加载主URL( http://www.example.com )。 这工作正常。

override fun webView[…]应该检测,如果一个超链接被点击,然后print("You clicked a hypelink!")超链接print("You clicked a hypelink!")

但不幸的是我得到以下错误:

一个错误和一个警告我的代码

我究竟做错了什么? 如何摆脱这些错误?

请尝试

为迅速3.0

  public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == .linkClicked { } return true; } 

迅速2.2

 internal func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == .LinkClicked { } return true; } 

这是工作的解决scheme(Xcode 7.3.1和Swift 2.2):

 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL?.query?.rangeOfString("target=external") != nil { if let url = request.URL { UIApplication.sharedApplication().openURL(url) return false } } return true } 

非常感谢来自freelancer.com的danhhgl !

我想你可以用这个代码解决:

  function reportBackToObjectiveC(string) { var iframe = document.createElement("iframe"); iframe.setAttribute("src", "callback://" + string); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } var links = document.getElementsByTagName("a"); for (var i=0; i<links.length; i++) { links[i].addEventListener("click", function() { reportBackToObjectiveC("link-clicked"); }, true); } 

在ios代码中:

 if ([[[request URL] scheme] isEqualToString:@"callback"]) { [self setNavigationLeavingCurrentPage:YES]; return NO; } 

更多的细节你可以从这里检查: