B2Fq
B2Fq

Reputation: 916

Error when click on a phone number or email address in TextView

I have code for working links and TextView could be edited.

And the links open in the application.

With links works, but with (Mail addresses, phone numbers) does not work

How can I fix this?


Error when click on a phone number or email address:

'NSInvalidArgumentException', reason: 'The specified URL has an unsupported scheme. Only HTTP and HTTPS URLs are supported.'


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
}

Upvotes: 2

Views: 639

Answers (1)

Upholder Of Truth
Upholder Of Truth

Reputation: 4711

The error you are seeing is because you are trying to open an email or phone number in Safari and it can't handle this type of scheme.

So I assume you want to open links in your Safari view controller and open emails and phone numbers with something else.

First change back to handling all links and then do something like this:

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
}

Upvotes: 3

Related Questions