网站建设资讯

NEWS

网站建设资讯

iOS检测文本中的URL、电话号码等信息-创新互联

要检测文本中的 URL、电话号码等,除了用正则表达式,还可以用 NSDataDetector。

成都创新互联公司专注于网站建设|成都网站维护|优化|托管以及网络推广,积累了大量的网站设计与制作经验,为许多企业提供了网站定制设计服务,案例作品覆盖纸箱等行业。能根据企业所处的行业与销售的产品,结合品牌形象的塑造,量身制作品质网站。
  1. 用 NSTextCheckingResult.CheckingType 初始化 NSDataDetector
  2. 调用 NSDataDetector 的 matches(in:options:range:) 方法获得 NSTextCheckingResult 数组
  3. 遍历 NSTextCheckingResult 数组,根据类型获取相应的检测结果,通过 range 获取结果文本在原文本中的位置范围(NSRange)

下面的例子是把 NSMutableAttributedString 中的 URL、电话号码突出显示。

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)
    }
  }
}

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前题目:iOS检测文本中的URL、电话号码等信息-创新互联
文章起源:http://cdweb.net/article/dggheo.html