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

用于初始化 NSDataDetector 的参数 types 的类型是 NSTextCheckingTypes,实际上是 UInt64。可以用或运算符连接多个值,以实现同时检测多种类型的文本。

public typealias NSTextCheckingTypes = UInt64

NSTextCheckingResult 的检测结果属性与类型有关。例如,当检测类型是 URL (resultType == .link),就可以通过 url 属性获取检测到的 URL。

给 NSMutableAttributedString 添加下划线,NSUnderlineStyleAttributeName 作为 key 对应的值在 Swift 中可以为 Int,不能为 NSUnderlineStyle。所以要写NSUnderlineStyle.styleSingle.rawValue。写NSUnderlineStyle.styleSingle会导致 NSMutableAttributedString 显示不出来。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持创新互联!

本文标题:iOS检测文本中的URL、电话号码等信息
标题链接:https://www.cdcxhl.com/article44/gipjhe.html

成都网站建设公司_创新互联,为您提供网站设计搜索引擎优化定制网站定制开发面包屑导航微信公众号

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都app开发公司