【问题标题】:Xcode, Swift: How to detect link click and stop redirecting Safari?Xcode,Swift:如何检测链接点击并停止重定向 Safari?
【发布时间】:2018-12-09 14:51:53
【问题描述】:

我创建了一个新的空白Single View Application 和一个包含链接https://example.com 的UITextView。

运行我的应用程序时,它会自动检测该链接并将其设为蓝色。单击此链接时,它将在 Apple Safari 浏览器中打开。

如何检测链接点击并停止重定向到 Safari?

我尝试了以下代码:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    print("Link clicked!")
    return false
}

很遗憾,我在控制台中没有收到 print("Link clicked!"),它仍在重定向到 Safari。

我做错了什么?

【问题讨论】:

    标签: ios swift xcode safari


    【解决方案1】:

    此代码将阻止 URL 在 Safari 中打开,并将在控制台中打印链接:

    import UIKit
    
    class ViewController: UIViewController, UITextViewDelegate {
    
        @IBOutlet var myTextViewAction: UITextView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myTextViewAction.delegate = self
        }
    
        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
            print("\nThis link was clicked: \(URL.absoluteString)\n")
            return false
        }
    }
    

    【讨论】:

    • 这是一个 UITextView,而不是 WebView。我想,这就是为什么webView() 没有被调用然后点击UITextView 中的链接的原因。
    • 好吧,那和你写的方法无关。
    • stackoverflow.com/a/20032788/8447312 看看这个答案,它的目标 C 但只是获取方法名称,并尝试查看是否可以阻止在 safari 中打开
    • @David 我已经更新了答案。我已经测试过了,它可以工作。请测试并接受我的回答。
    • @David URL.absoluteString 在该委托方法中
    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2017-09-10
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多