单击TextView中的电话号码或电子邮件地址时出错

时间:2017-12-31 11:09:19

标签: ios swift hyperlink

我有工作链接的代码,可以编辑TextView。

链接在应用程序中打开。

链接有效,但(邮件地址,电话号码)不起作用

我该如何解决这个问题?

点击电话号码或电子邮件地址时出错:

' NSInvalidArgumentException',原因:'指定的网址具有不受支持的方案。仅支持HTTP和HTTPS网址。'

import SafariServices

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    // Open links with a SFSafariViewController instance and return false to prevent the system to open Safari app
    let safariViewController = SFSafariViewController(url: URL)
    present(safariViewController, animated: true, completion: nil)
    return false
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
@objc func viewTapped(_ aRecognizer: UITapGestureRecognizer) {
    self.view.endEditing(true)
}
// when you tap on your textView you set the property isEditable to true and you´ll be able to edit the text. If you click on a link you´ll browse to that link instead
@objc func textViewTapped(_ aRecognizer: UITapGestureRecognizer) {
    viewText.dataDetectorTypes = []
    viewText.isEditable = true
    viewText.becomeFirstResponder()
}
// this delegate method restes the isEditable property when your done editing
func textViewDidEndEditing(_ textView: UITextView) {
    viewText.isEditable = false
    //viewText.dataDetectorTypes = .all
    viewText.dataDetectorTypes = .link
}

1 个答案:

答案 0 :(得分:2)

您看到的错误是因为您尝试在Safari中打开电子邮件或电话号码,而且无法处理此类方案。

因此,我假设您要在Safari视图控制器中打开链接,并使用其他内容打开电子邮件和电话号码。

首先改回处理所有链接,然后执行以下操作:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if (URL.scheme?.contains("mailto"))! {
        // Handle emails here
    } else if (URL.scheme?.contains("tel"))! {
        // Handle phone numbers here
    } else if (URL.scheme?.contains("http"))! || (URL.scheme?.contains("https"))! {
        // Handle links
        let safariViewController = SFSafariViewController(url: URL)
        present(safariViewController, animated: true, completion: nil)
    } else {
        // Handle anything else that has slipped through.
    }

    return false
}