iOS检测文本中的URL、电话号码等信息-创新互联
要检测文本中的 URL、电话号码等,除了用正则表达式,还可以用 NSDataDetector。

- 用 NSTextCheckingResult.CheckingType 初始化 NSDataDetector
- 调用 NSDataDetector 的 matches(in:options:range:) 方法获得 NSTextCheckingResult 数组
- 遍历 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、电话号码等信息-创新互联
网页URL:http://www.jxjierui.cn/article/dggheo.html


咨询
建站咨询
