我需要检测是否以及何时键入了完整的URL,因此我可以请求获取该URL的一些元数据。 当用户粘贴URL(可能是大多数用例)时,这也应该起作用
现在,我正在使用下面的代码检查给定的文本块是否具有URL,并从中提取URL。
extension String {
func extractUrlsFromString() -> [String] {
let types: NSTextCheckingResult.CheckingType = .link
let detector = try? NSDataDetector(types: types.rawValue)
var urlStrings = [String]()
guard let detect = detector else {
return []
}
let matches = detect.matches(in: self, options: .reportCompletion, range: NSMakeRange(0, self.count))
for match in matches {
if let string = match.url?.absoluteString {
urlStrings.append(string)
}
}
return urlStrings
}
}
这是我从默认的UITextViewDelegate方法调用的
func textViewDidChange(_ textView: UITextView) {
let urls = textView.text.extractUrlsFromString()
if !urls.isEmpty, let url = urls.first {
// Make API Call to get Metadata for the first URL found
}
}
在许多方面,这种方法似乎效率极低。 我想更改/改善的几件事
谢谢!