iOS detects information such as URL phone number and so on in text

  • 2021-12-11 09:11:43
  • OfStack

To detect URL, phone numbers, etc. in text, you can use NSDataDetector in addition to regular expressions.

Initialize NSDataDetector with NSTextCheckingResult. CheckingType Call the matches (in: options: range:) method of NSDataDetector to get the NSTextCheckingResult array Traverse the NSTextCheckingResult array, get the corresponding detection result according to the type, and get the position range of the result text in the original text through range (NSRange)

The following example is to highlight the URL, telephone number in NSMutableAttributedString.


func showAttributedStringLink(_ attributedStr: NSMutableAttributedString) {
  // We check URL and phone number
  let types: UInt64 = NSTextCheckingResult.CheckingType.link.rawValue | NSTextCheckingResult.CheckingType.phoneNumber.rawValue
  // Get NSDataDetector
  guard let detector: NSDataDetector = try? NSDataDetector(types: types) else { return }
  // Get NSTextCheckingResult array
  let matches: [NSTextCheckingResult] = detector.matches(in: attributedStr.string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: attributedStr.length))
  // Go through and check result
  for match in matches {
    if match.resultType == .link, let url = match.url {
      // Get URL
      attributedStr.addAttributes([ NSLinkAttributeName : url,
                     NSForegroundColorAttributeName : UIColor.blue,
                     NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue ],
                    range: match.range)
    } else if match.resultType == .phoneNumber, let phoneNumber = match.phoneNumber {
      // Get phone number
      attributedStr.addAttributes([ NSLinkAttributeName : phoneNumber,
                     NSForegroundColorAttributeName : UIColor.blue,
                     NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue ],
                    range: match.range)
    }
  }
}

The parameter types used to initialize NSDataDetector is of type NSTextCheckingTypes and is actually UInt64. You can join multiple values with the OR operator to detect multiple types of text at the same time.

public typealias NSTextCheckingTypes = UInt64

The test result attribute of NSTextCheckingResult is related to the type. For example, when the instrumentation type is URL (resultType = =. link), the detected URL can be obtained through the url attribute.

Add an underline to NSMutableAttributedString, and NSUnderlineStyleAttributeName, as the corresponding value of key, can be Int in Swift, but not NSUnderlineStyle. So I have to write NSUnderlineStyle.styleSingle.rawValue . Write NSUnderlineStyle.styleSingle It will cause NSMutableAttributedString to not be displayed.


Related articles: