Xcode,斯威夫特;检测 UIWebView 中的超链接点击 [英] Xcode, Swift; Detect hyperlink click in UIWebView
问题描述
我用 Xcode 和 Swift 制作了一个 iOS 应用.
我想在 Safari 浏览器中打开特定的超链接,在 WebView 本身还有其他的.
要达到此目的,我必须检查超链接何时被点击.
这是我目前的代码:
<代码>////PushViewController.swift// 应用程序////导入 UIKit类 PushViewController: UIViewController, UIWebViewDelegate {@IBOutlet var openpushmessage:UIWebView!var weburl:String = "http://www.example.com"覆盖 func viewDidLoad() {super.viewDidLoad()让 url: NSURL = NSURL(string: weburl)!让 requestURL: NSURLRequest = NSURLRequest(URL: url)openpushmessage.loadRequest(requestURL)}覆盖 func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) ->布尔{如果 navigationType == .linkClicked{打印(你点击了一个超链接!")}返回真}}
viewDidLoad()
中的代码打开加载主 URL (
我做错了什么?如何摆脱这些错误?
这是可行的解决方案(Xcode 7.3.1 和 Swift 2.2):
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) ->布尔{如果 request.URL?.query?.rangeOfString("target=external") != nil {如果让 url = request.URL {UIApplication.sharedApplication().openURL(url)返回假}}返回真}
非常感谢 来自 freelancer.com 的 danhhgl!
I made an iOS app with Xcode and Swift.
I want to open specific hyperlinks in Safari browser, there others in the WebView itself.
To reach this, I'll have to check when an hyperlinks gets clicked.
This is the code I have so far:
//
// 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
}
}
The code in viewDidLoad()
opens the loads the main URL (http://www.example.com) from my server. That works fine.
override fun webView[…]
should detect if a hyperlink is clicked and then print("You clicked a hypelink!")
.
But unfortunately I'm getting the following errors:
What am I doing wrong? How to get rid of these errors?
This is the working solution (Xcode 7.3.1 and 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
}
Many thanks to danhhgl from freelancer.com!
这篇关于Xcode,斯威夫特;检测 UIWebView 中的超链接点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!