iosswiftuitextviewuitextviewdelegatedatadetectortypes

How to intercept a phone number click (Call button) on link in UITextView?


Is there a callback to identify when the user clicks Call in the Popup that comes when we click on a number in a textview?

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool

The function mentioned above will help me identify that a link has been clicked in a UITextView, Whereas is there a specific callback to identify if Call is clicked or Cancel is clicked


Solution

  • Use the delegate method:

    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
            print("Phone \(URL)")
            return false
    }
    

    don't forget to connect the textView delegate.

    self.textView.delegate = self
    

    Then you can add a custom UIAlertController to call or cancel.

    Edit:

    This is the full code:

    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
    
        if (URL.scheme == "tel"){
            let phoneNumber = URL.absoluteString.stringByReplacingOccurrencesOfString("tel:", withString: "")
            let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "Call", style: .Default, handler: { (alert) in
                if UIApplication.sharedApplication().canOpenURL(URL) {
                    UIApplication.sharedApplication().openURL(URL)
                }
            }))
            alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert) in
                print("User Canceld")
            }))
            presentViewController(alert, animated: true, completion: nil)
            return false
        }
    
        return true
    }
    

    One last thing,, in your info.plist add:

    <key>LSApplicationQueriesSchemes</key>
    <array>
    <string>tel</string>
    </array>