我用 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!")
。
但不幸的是我收到以下错误:
我做错了什么?如何消除这些错误?
请尝试
适用于 swift 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;
}
这是有效的解决方案(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;
}
更多详情您可以从这里查看:
使用 xCode v15.0,我必须进行以下调整才能使链接激活工作......
public func webView(_ webView: WKWebView, shouldStartLoadWith request: URLRequest, navigationType: WKNavigationType) -> Bool
{
if navigationType == .linkActivated {}
return true;
}
享受 - Dougster