在用户在TextView中键入/粘贴URL时实时检测URL

时间:2018-12-31 13:46:12

标签: ios swift

我需要检测是否以及何时键入了完整的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
    }
}

在许多方面,这种方法似乎效率极低。 我想更改/改善的几件事

  1. 仅在需要时,我想调用该函数以提取URL(此条件是在满足特定字符限制时或在用户粘贴之后。.等)
  2. 我还想知道是否有更好的方法来检测URL,以及当前方法是否过于密集。
  3. 处理用户编辑URL的情况,以避免对同一URL进行多次API调用。

谢谢!

0 个答案:

没有答案