Crashalot
Crashalot

Reputation: 34513

iOS: Extract detected numbers and links from UITextView?

This question and similar ones address how to detect phone numbers and links inside of a UITextView.

Once detected, is there a way to extract the detected numbers and links?

The goal is to use UITextView to detect numbers and links instead of rebuilding this logic.

To clarify, the ideal workflow is:

  1. User enters text into UITextView.
  2. UITextView detects numbers and links.
  3. Extract numbers and links from text.

Upvotes: 0

Views: 105

Answers (1)

Dare
Dare

Reputation: 2587

UITextView really just makes the process of data detection easier to implement for user clickable links. If you are trying to extract and work with that data I would likely recommend implementing it to handle your specific use case. Data detection is luckily very straightforward.

let string = "www.google.com / (555) 123-4567"

let types: NSTextCheckingResult.CheckingType = [.phoneNumber, .link]
let detector = try NSDataDetector(types: types.rawValue)
let range = NSMakeRange(0, string.count)
detector.enumerateMatches(in: string, options: [], range: range) { result, _, _ in
   print(result)
}

Output:

Optional(<NSLinkCheckingResult: 0x6000031264c0>{0, 14}{http://www.google.com})
Optional(<NSPhoneNumberCheckingResult: 0x600003f384b0>{17, 14}{(555) 123-4567})

Upvotes: 1

Related Questions